Imported Upstream version 2.7.10 48/138348/1 upstream/2.7.10
authorDongHun Kwak <dh0128.kwak@samsung.com>
Wed, 12 Jul 2017 02:05:23 +0000 (11:05 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Wed, 12 Jul 2017 02:05:31 +0000 (11:05 +0900)
Change-Id: I71e04a6e83b31198e3aff21913814359e60b7843
Signed-off-by: DongHun Kwak <dh0128.kwak@samsung.com>
374 files changed:
Demo/turtle/turtleDemo.py
Doc/Makefile
Doc/c-api/buffer.rst
Doc/c-api/exceptions.rst
Doc/c-api/init.rst
Doc/c-api/structures.rst
Doc/c-api/unicode.rst
Doc/copyright.rst
Doc/distutils/apiref.rst
Doc/extending/extending.rst
Doc/glossary.rst
Doc/howto/logging-cookbook.rst
Doc/howto/pyporting.rst
Doc/howto/unicode.rst
Doc/howto/webservers.rst
Doc/library/argparse.rst
Doc/library/cmath.rst
Doc/library/codecs.rst
Doc/library/copy_reg.rst
Doc/library/datetime.rst
Doc/library/decimal.rst
Doc/library/dis.rst
Doc/library/fnmatch.rst
Doc/library/ftplib.rst
Doc/library/functions.rst
Doc/library/heapq.rst
Doc/library/htmllib.rst
Doc/library/httplib.rst
Doc/library/idle.rst
Doc/library/index.rst
Doc/library/json.rst
Doc/library/logging.config.rst
Doc/library/logging.handlers.rst
Doc/library/logging.rst
Doc/library/mimetypes.rst
Doc/library/multiprocessing.rst
Doc/library/othergui.rst
Doc/library/profile.rst
Doc/library/pydoc.rst
Doc/library/re.rst
Doc/library/runpy.rst
Doc/library/sgmllib.rst
Doc/library/shutil.rst
Doc/library/ssl.rst
Doc/library/stdtypes.rst
Doc/library/time.rst
Doc/library/tkinter.rst
Doc/library/unittest.rst
Doc/library/urllib.rst
Doc/library/urllib2.rst
Doc/library/xml.etree.elementtree.rst
Doc/library/zipfile.rst
Doc/license.rst
Doc/make.bat
Doc/reference/datamodel.rst
Doc/tools/static/basic.css
Doc/tutorial/datastructures.rst
Doc/tutorial/interpreter.rst
Doc/tutorial/introduction.rst
Doc/using/cmdline.rst
Include/patchlevel.h
Include/pyerrors.h
LICENSE
Lib/Cookie.py
Lib/SimpleHTTPServer.py
Lib/_LWPCookieJar.py
Lib/_abcoll.py
Lib/_pyio.py
Lib/_strptime.py
Lib/aifc.py
Lib/binhex.py
Lib/bsddb/test/test_all.py
Lib/bsddb/test/test_basics.py
Lib/bsddb/test/test_dbshelve.py
Lib/bsddb/test/test_get_none.py
Lib/bsddb/test/test_queue.py
Lib/bsddb/test/test_recno.py
Lib/chunk.py
Lib/codecs.py
Lib/collections.py
Lib/cookielib.py
Lib/ctypes/macholib/fetch_macholib.bat
Lib/ctypes/test/test_find.py
Lib/ctypes/test/test_pickling.py
Lib/ctypes/test/test_pointers.py
Lib/ctypes/util.py
Lib/distutils/__init__.py
Lib/distutils/command/check.py
Lib/distutils/dir_util.py
Lib/distutils/tests/test_check.py
Lib/distutils/text_file.py
Lib/dumbdbm.py
Lib/encodings/uu_codec.py
Lib/ensurepip/__init__.py
Lib/ensurepip/_bundled/pip-1.5.6-py2.py3-none-any.whl [deleted file]
Lib/ensurepip/_bundled/pip-6.1.1-py2.py3-none-any.whl [new file with mode: 0644]
Lib/ensurepip/_bundled/setuptools-15.2-py2.py3-none-any.whl [moved from Lib/ensurepip/_bundled/setuptools-7.0-py2.py3-none-any.whl with 60% similarity]
Lib/fileinput.py
Lib/fnmatch.py
Lib/ftplib.py
Lib/genericpath.py
Lib/gettext.py
Lib/gzip.py
Lib/hashlib.py
Lib/htmlentitydefs.py
Lib/httplib.py
Lib/idlelib/CodeContext.py
Lib/idlelib/EditorWindow.py
Lib/idlelib/FormatParagraph.py
Lib/idlelib/PyShell.py
Lib/idlelib/SearchEngine.py
Lib/idlelib/config-extensions.def
Lib/idlelib/config-main.def
Lib/idlelib/configDialog.py
Lib/idlelib/help.txt
Lib/idlelib/idle.bat
Lib/idlelib/idle_test/test_calltips.py
Lib/idlelib/idle_test/test_io.py [new file with mode: 0644]
Lib/idlelib/idlever.py
Lib/idlelib/testcode.py [deleted file]
Lib/imaplib.py
Lib/lib-tk/Tkinter.py
Lib/lib-tk/test/test_tkinter/test_variables.py
Lib/lib-tk/test/test_tkinter/test_widgets.py
Lib/lib-tk/test/test_ttk/support.py
Lib/lib-tk/test/test_ttk/test_widgets.py
Lib/lib-tk/ttk.py
Lib/lib-tk/turtle.py
Lib/lib2to3/fixes/fix_exitfunc.py
Lib/linecache.py
Lib/logging/__init__.py
Lib/logging/handlers.py
Lib/macpath.py
Lib/mailbox.py
Lib/mimetypes.py
Lib/modulefinder.py
Lib/multiprocessing/connection.py
Lib/multiprocessing/pool.py
Lib/multiprocessing/queues.py
Lib/multiprocessing/sharedctypes.py
Lib/ntpath.py
Lib/os.py
Lib/os2emxpath.py
Lib/posixpath.py
Lib/py_compile.py
Lib/pydoc.py
Lib/pydoc_data/topics.py
Lib/rfc822.py
Lib/shelve.py
Lib/shutil.py
Lib/site.py
Lib/smtplib.py
Lib/socket.py
Lib/sre_parse.py
Lib/ssl.py
Lib/string.py
Lib/tarfile.py
Lib/telnetlib.py
Lib/tempfile.py
Lib/test/_mock_backport.py
Lib/test/audiotests.py
Lib/test/dh1024.pem [new file with mode: 0644]
Lib/test/dh512.pem [deleted file]
Lib/test/lock_tests.py
Lib/test/regrtest.py
Lib/test/test__locale.py
Lib/test/test_aifc.py
Lib/test/test_argparse.py
Lib/test/test_bigmem.py
Lib/test/test_binascii.py
Lib/test/test_bool.py
Lib/test/test_bz2.py
Lib/test/test_calendar.py
Lib/test/test_capi.py
Lib/test/test_cfgparser.py
Lib/test/test_codeccallbacks.py
Lib/test/test_codecs.py
Lib/test/test_collections.py
Lib/test/test_cookie.py
Lib/test/test_cookielib.py
Lib/test/test_csv.py
Lib/test/test_datetime.py
Lib/test/test_decimal.py
Lib/test/test_deque.py
Lib/test/test_descr.py
Lib/test/test_doctest.py
Lib/test/test_docxmlrpc.py
Lib/test/test_dumbdbm.py
Lib/test/test_exceptions.py
Lib/test/test_file2k.py
Lib/test/test_fileio.py
Lib/test/test_float.py
Lib/test/test_ftplib.py
Lib/test/test_functools.py
Lib/test/test_gc.py
Lib/test/test_gdb.py
Lib/test/test_genericpath.py
Lib/test/test_gettext.py
Lib/test/test_gzip.py
Lib/test/test_httplib.py
Lib/test/test_httpservers.py
Lib/test/test_io.py
Lib/test/test_itertools.py
Lib/test/test_linecache.py
Lib/test/test_macpath.py
Lib/test/test_marshal.py
Lib/test/test_memoryio.py
Lib/test/test_minidom.py
Lib/test/test_multibytecodec.py
Lib/test/test_multibytecodec_support.py
Lib/test/test_multiprocessing.py
Lib/test/test_ntpath.py
Lib/test/test_os.py
Lib/test/test_pdb.py
Lib/test/test_pep292.py
Lib/test/test_posix.py
Lib/test/test_posixpath.py
Lib/test/test_pydoc.py
Lib/test/test_random.py
Lib/test/test_re.py
Lib/test/test_readline.py
Lib/test/test_rfc822.py
Lib/test/test_sax.py
Lib/test/test_set.py
Lib/test/test_sets.py
Lib/test/test_shutil.py
Lib/test/test_ssl.py
Lib/test/test_string.py
Lib/test/test_stringprep.py
Lib/test/test_strptime.py
Lib/test/test_struct.py
Lib/test/test_sundry.py
Lib/test/test_support.py
Lib/test/test_sys.py
Lib/test/test_sys_settrace.py
Lib/test/test_tcl.py
Lib/test/test_threadedtempfile.py
Lib/test/test_threading.py
Lib/test/test_threading_local.py
Lib/test/test_timeit.py [new file with mode: 0644]
Lib/test/test_unicode.py
Lib/test/test_urllib.py
Lib/test/test_urllib2.py
Lib/test/test_urllib2_localnet.py
Lib/test/test_urllib2net.py
Lib/test/test_uuid.py
Lib/test/test_warnings.py
Lib/test/test_xpickle.py
Lib/test/test_zipfile.py
Lib/test/xmltestdata/test.xml
Lib/test/xmltestdata/test.xml.out
Lib/textwrap.py
Lib/timeit.py
Lib/types.py
Lib/unittest/case.py
Lib/unittest/test/test_case.py
Lib/urllib.py
Lib/warnings.py
Lib/wave.py
Lib/xml/sax/expatreader.py
Lib/xmlrpclib.py
Mac/BuildScript/README.txt
Mac/BuildScript/build-installer.py
Mac/BuildScript/openssl_sdk_makedepend.patch
Mac/BuildScript/resources/License.rtf [moved from Mac/BuildScript/resources/license.rtf with 92% similarity]
Mac/BuildScript/resources/ReadMe.rtf [moved from Mac/BuildScript/resources/readme.rtf with 92% similarity]
Mac/BuildScript/resources/ReadMe.txt [deleted file]
Mac/BuildScript/resources/Welcome.rtf
Mac/IDLE/Info.plist.in
Mac/PythonLauncher/Info.plist.in
Mac/Resources/app/Info.plist.in
Mac/Resources/framework/Info.plist.in
Makefile.pre.in
Misc/ACKS
Misc/NEWS
Misc/README
Misc/RPM/README [deleted file]
Misc/RPM/python-2.7.spec [deleted file]
Misc/SpecialBuilds.txt
Misc/python.man
Modules/Setup.dist
Modules/_collectionsmodule.c
Modules/_ctypes/_ctypes.c
Modules/_ctypes/libffi/src/x86/ffi.c
Modules/_ctypes/stgdict.c
Modules/_functoolsmodule.c
Modules/_heapqmodule.c
Modules/_io/_iomodule.c
Modules/_io/bufferedio.c
Modules/_io/fileio.c
Modules/_io/textio.c
Modules/_localemodule.c
Modules/_sqlite/connection.c
Modules/_ssl.c
Modules/_ssl_data.h
Modules/_struct.c
Modules/_testcapimodule.c
Modules/_tkinter.c
Modules/cjkcodecs/_codecs_cn.c
Modules/cjkcodecs/_codecs_hk.c
Modules/cjkcodecs/_codecs_kr.c
Modules/cjkcodecs/cjkcodecs.h
Modules/cjkcodecs/multibytecodec.c
Modules/cmathmodule.c
Modules/itertoolsmodule.c
Modules/mathmodule.c
Modules/posixmodule.c
Modules/readline.c
Modules/socketmodule.c
Modules/tkinter.h
Modules/unicodedata.c
Objects/abstract.c
Objects/floatobject.c
Objects/listobject.c
Objects/obmalloc.c
Objects/tupleobject.c
Objects/typeobject.c
Objects/unicodeobject.c
Objects/weakrefobject.c
PC/VC6/rt.bat
PC/VS7.1/amd64_ml64.bat
PC/VS7.1/build_ssl.bat
PC/VS7.1/rt.bat
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/rt.bat
PC/python_nt.rc
PCbuild/build.bat
PCbuild/build_env.bat
PCbuild/build_pgo.bat
PCbuild/build_ssl.bat
PCbuild/build_ssl.py
PCbuild/env.bat
PCbuild/idle.bat
PCbuild/pyproject.vsprops
PCbuild/readme.txt
PCbuild/rt.bat
Python/ceval.c
Python/compile.c
Python/errors.c
Python/frozenmain.c
Python/getcopyright.c
Python/import.c
Python/peephole.c
Python/pystrtod.c
Python/random.c
Python/thread.c
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/freeze/bkfile.py
Tools/msi/msi.py
Tools/msi/uuids.py
Tools/scripts/ftpmirror.py [deleted file]
Tools/scripts/h2py.py
Tools/ssl/make_ssl_data.py
Tools/unicode/genwincodecs.bat
aclocal.m4 [new file with mode: 0644]
configure
configure.ac
pyconfig.h.in
setup.py

index d284042..12b4355 100755 (executable)
@@ -231,6 +231,8 @@ class DemoWindow(object):
             else:
                 self.state = DONE
         except turtle.Terminator:
+            if self.root is None:
+                return
             self.state = DONE
             result = "stopped!"
         if self.state == DONE:
@@ -257,7 +259,9 @@ class DemoWindow(object):
             turtle.TurtleScreen._RUNNING = False
 
     def _destroy(self):
+        turtle.TurtleScreen._RUNNING = False
         self.root.destroy()
+        self.root = None
         #sys.exit()
 
 def main():
index 5b5f68a..ea30231 100644 (file)
@@ -8,7 +8,7 @@ PYTHON       = python
 SPHINXBUILD  = sphinx-build
 PAPER        =
 SOURCES      =
-DISTVERSION  = $(shell $(PYTHON) tools/patchlevel.py)
+DISTVERSION  = $(shell $(PYTHON) tools/extensions/patchlevel.py)
 
 ALLSPHINXOPTS = -b $(BUILDER) -d build/doctrees -D latex_paper_size=$(PAPER) \
                 $(SPHINXOPTS) . build/$(BUILDER) $(SOURCES)
index 74693ac..e36d01f 100644 (file)
@@ -98,8 +98,11 @@ The new-style Py_buffer struct
       suboffset value that it negative indicates that no de-referencing should
       occur (striding in a contiguous memory block).
 
+      If all suboffsets are negative (i.e. no de-referencing is needed, then
+      this field must be NULL (the default value).
+
       Here is a function that returns a pointer to the element in an N-D array
-      pointed to by an N-dimesional index when there are both non-NULL strides
+      pointed to by an N-dimensional index when there are both non-NULL strides
       and suboffsets::
 
           void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
index 91964d0..6f8f243 100644 (file)
@@ -70,7 +70,7 @@ is a separate error indicator for each thread.
       Do not compare the return value to a specific exception; use
       :c:func:`PyErr_ExceptionMatches` instead, shown below.  (The comparison could
       easily fail since the exception may be an instance instead of a class, in the
-      case of a class exception, or it may the a subclass of the expected exception.)
+      case of a class exception, or it may be a subclass of the expected exception.)
 
 
 .. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
index 46fc93f..d78b43d 100644 (file)
@@ -642,7 +642,7 @@ with sub-interpreters:
    .. versionadded:: 2.3
 
 
-.. c:function:: PyThreadState PyGILState_GetThisThreadState()
+.. c:function:: PyThreadState* PyGILState_GetThisThreadState()
 
    Get the current thread state for this thread.  May return ``NULL`` if no
    GILState API has been used on the current thread.  Note that the main thread
@@ -1136,7 +1136,7 @@ These functions are only intended to be used by advanced debugging tools.
 
 .. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)
 
-   Return the pointer to the first :c:type:`PyThreadState` object in the list of
+   Return the pointer to the first :c:type:`PyThreadState` object in the list of
    threads associated with the interpreter *interp*.
 
    .. versionadded:: 2.2
index e31687f..c193510 100644 (file)
@@ -122,7 +122,7 @@ The :attr:`ml_meth` is a C function pointer.  The functions may be of different
 types, but they always return :c:type:`PyObject\*`.  If the function is not of
 the :c:type:`PyCFunction`, the compiler will require a cast in the method table.
 Even though :c:type:`PyCFunction` defines the first parameter as
-:c:type:`PyObject\*`, it is common that the method implementation uses the
+:c:type:`PyObject\*`, it is common that the method implementation uses the
 specific C type of the *self* object.
 
 The :attr:`ml_flags` field is a bitfield which can include the following flags.
index 8932915..13a2807 100644 (file)
@@ -547,7 +547,7 @@ These are the UTF-32 codec APIs:
    After completion, *\*byteorder* is set to the current byte order at the end
    of input data.
 
-   In a narrow build codepoints outside the BMP will be decoded as surrogate pairs.
+   In a narrow build code points outside the BMP will be decoded as surrogate pairs.
 
    If *byteorder* is *NULL*, the codec starts in native order mode.
 
@@ -580,7 +580,7 @@ These are the UTF-32 codec APIs:
    mark (U+FEFF). In the other two modes, no BOM mark is prepended.
 
    If *Py_UNICODE_WIDE* is not defined, surrogate pairs will be output
-   as a single codepoint.
+   as a single code point.
 
    Return *NULL* if an exception was raised by the codec.
 
index be47e8a..2b2f887 100644 (file)
@@ -4,7 +4,7 @@ Copyright
 
 Python and this documentation is:
 
-Copyright © 2001-2014 Python Software Foundation. All rights reserved.
+Copyright © 2001-2015 Python Software Foundation. All rights reserved.
 
 Copyright © 2000 BeOpen.com. All rights reserved.
 
index 2a75a46..8366d8a 100644 (file)
@@ -970,7 +970,7 @@ directories.
 .. function:: create_tree(base_dir, files[, mode=0777, verbose=0, dry_run=0])
 
    Create all the empty directories under *base_dir* needed to put *files* there.
-   *base_dir* is just the name of a directory which doesn't necessarily exist
+   *base_dir* is just the name of a directory which doesn't necessarily exist
    yet; *files* is a list of filenames to be interpreted relative to *base_dir*.
    *base_dir* + the directory portion of every file in *files* will be created if
    it doesn't already exist.  *mode*, *verbose* and *dry_run* flags  are as for
index 5488ce9..4b23463 100644 (file)
@@ -20,12 +20,17 @@ source file by including the header ``"Python.h"``.
 The compilation of an extension module depends on its intended use as well as on
 your system setup; details are given in later chapters.
 
-Do note that if your use case is calling C library functions or system calls,
-you should consider using the :mod:`ctypes` module rather than writing custom
-C code. Not only does :mod:`ctypes` let you write Python code to interface
-with C code, but it is more portable between implementations of Python than
-writing and compiling an extension module which typically ties you to CPython.
+.. note::
 
+   The C extension interface is specific to CPython, and extension modules do
+   not work on other Python implementations.  In many cases, it is possible to
+   avoid writing C extensions and preserve portability to other implementations.
+   For example, if your use case is calling C library functions or system calls,
+   you should consider using the :mod:`ctypes` module or the `cffi
+   <http://cffi.readthedocs.org>`_ library rather than writing custom C code.
+   These modules let you write Python code to interface with C code and are more
+   portable between implementations of Python than writing and compiling a C
+   extension module.
 
 
 .. _extending-simpleexample:
index 5d69dd4..010fdf2 100644 (file)
@@ -284,7 +284,7 @@ Glossary
    generator
       A function which returns an iterator.  It looks like a normal function
       except that it contains :keyword:`yield` statements for producing a series
-      a values usable in a for-loop or that can be retrieved one at a time with
+      of values usable in a for-loop or that can be retrieved one at a time with
       the :func:`next` function. Each :keyword:`yield` temporarily suspends
       processing, remembering the location execution state (including local
       variables and pending try-statements).  When the generator resumes, it
index 69fdcca..f0a3221 100644 (file)
@@ -1059,3 +1059,112 @@ A couple of extra points to note:
   information on how logging supports using user-defined objects in its
   configuration, and see the other cookbook recipe :ref:`custom-handlers` above.
 
+
+.. _custom-format-exception:
+
+Customized exception formatting
+-------------------------------
+
+There might be times when you want to do customized exception formatting - for
+argument's sake, let's say you want exactly one line per logged event, even
+when exception information is present. You can do this with a custom formatter
+class, as shown in the following example::
+
+    import logging
+
+    class OneLineExceptionFormatter(logging.Formatter):
+        def formatException(self, exc_info):
+            """
+            Format an exception so that it prints on a single line.
+            """
+            result = super(OneLineExceptionFormatter, self).formatException(exc_info)
+            return repr(result) # or format into one line however you want to
+
+        def format(self, record):
+            s = super(OneLineExceptionFormatter, self).format(record)
+            if record.exc_text:
+                s = s.replace('\n', '') + '|'
+            return s
+
+    def configure_logging():
+        fh = logging.FileHandler('output.txt', 'w')
+        f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
+                                      '%d/%m/%Y %H:%M:%S')
+        fh.setFormatter(f)
+        root = logging.getLogger()
+        root.setLevel(logging.DEBUG)
+        root.addHandler(fh)
+
+    def main():
+        configure_logging()
+        logging.info('Sample message')
+        try:
+            x = 1 / 0
+        except ZeroDivisionError as e:
+            logging.exception('ZeroDivisionError: %s', e)
+
+    if __name__ == '__main__':
+        main()
+
+When run, this produces a file with exactly two lines::
+
+    28/01/2015 07:21:23|INFO|Sample message|
+    28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|
+
+While the above treatment is simplistic, it points the way to how exception
+information can be formatted to your liking. The :mod:`traceback` module may be
+helpful for more specialized needs.
+
+.. _spoken-messages:
+
+Speaking logging messages
+-------------------------
+
+There might be situations when it is desirable to have logging messages rendered
+in an audible rather than a visible format. This is easy to do if you have text-
+to-speech (TTS) functionality available in your system, even if it doesn't have
+a Python binding. Most TTS systems have a command line program you can run, and
+this can be invoked from a handler using :mod:`subprocess`. It's assumed here
+that TTS command line programs won't expect to interact with users or take a
+long time to complete, and that the frequency of logged messages will be not so
+high as to swamp the user with messages, and that it's acceptable to have the
+messages spoken one at a time rather than concurrently, The example implementation
+below waits for one message to be spoken before the next is processed, and this
+might cause other handlers to be kept waiting. Here is a short example showing
+the approach, which assumes that the ``espeak`` TTS package is available::
+
+    import logging
+    import subprocess
+    import sys
+
+    class TTSHandler(logging.Handler):
+        def emit(self, record):
+            msg = self.format(record)
+            # Speak slowly in a female English voice
+            cmd = ['espeak', '-s150', '-ven+f3', msg]
+            p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+                                 stderr=subprocess.STDOUT)
+            # wait for the program to finish
+            p.communicate()
+
+    def configure_logging():
+        h = TTSHandler()
+        root = logging.getLogger()
+        root.addHandler(h)
+        # the default formatter just returns the message
+        root.setLevel(logging.DEBUG)
+
+    def main():
+        logging.info('Hello')
+        logging.debug('Goodbye')
+
+    if __name__ == '__main__':
+        configure_logging()
+        sys.exit(main())
+
+When run, this script should say "Hello" and then "Goodbye" in a female voice.
+
+The above approach can, of course, be adapted to other TTS systems and even
+other systems altogether which can process messages via external programs run
+from a command line.
+
index 212853e..bd80dfd 100644 (file)
@@ -19,599 +19,374 @@ Porting Python 2 Code to Python 3
    If you would like to read one core Python developer's take on why Python 3
    came into existence, you can read Nick Coghlan's `Python 3 Q & A`_.
 
-   If you prefer to read a (free) book on porting a project to Python 3,
-   consider reading `Porting to Python 3`_ by Lennart Regebro which should cover
-   much of what is discussed in this HOWTO.
-
    For help with porting, you can email the python-porting_ mailing list with
    questions.
 
-The Short Version
-=================
-
-* Decide what's the oldest version of Python 2 you want to support (if at all)
-* Make sure you have a thorough test suite and use continuous integration
-  testing to make sure you stay compatible with the versions of Python you care
-  about
-* If you have dependencies, check their Python 3 status using caniusepython3
-  (`command-line tool <https://pypi.python.org/pypi/caniusepython3>`__,
-  `web app <https://caniusepython3.com/>`__)
-
-With that done, your options are:
-
-* If you are dropping Python 2 support, use :ref:`2to3 <2to3-reference>` to port
-  to Python 3
-
-* If you are keeping Python 2 support, then start writing Python 2/3-compatible
-  code starting **TODAY**
-
-  + If you have dependencies that have not been ported, reach out to them to port
-    their project while working to make your code compatible with Python 3 so
-    you're ready when your dependencies are all ported
-  + If all your dependencies have been ported (or you have none), go ahead and
-    port to Python 3
-
-* If you are creating a new project that wants to have 2/3 compatibility,
-  code in Python 3 and then backport to Python 2
-
-
-Before You Begin
-================
-
-If your project is on the Cheeseshop_/PyPI_, make sure it has the proper
-`trove classifiers`_ to signify what versions of Python it **currently**
-supports. At minimum you should specify the major version(s), e.g.
-``Programming Language :: Python :: 2`` if your project currently only supports
-Python 2. It is preferrable that you be as specific as possible by listing every
-major/minor version of Python that you support, e.g. if your project supports
-Python 2.6 and 2.7, then you want the classifiers of::
-
- Programming Language :: Python :: 2
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
-
-Once your project supports Python 3 you will want to go back and add the
-appropriate classifiers for Python 3 as well. This is important as setting the
-``Programming Language :: Python :: 3`` classifier will lead to your project
-being listed under the `Python 3 Packages`_ section of PyPI.
-
-Make sure you have a robust test suite. You need to
-make sure everything continues to work, just like when you support a new
-minor/feature release of Python. This means making sure your test suite is
-thorough and is ported properly between Python 2 & 3 (consider using coverage_
-to measure that you have effective test coverage). You will also most likely
-want to use something like tox_ to automate testing between all of your
-supported versions of Python. You will also want to **port your tests first** so
-that you can make sure that you detect breakage during the transition. Tests also
-tend to be simpler than the code they are testing so it gives you an idea of how
-easy it can be to port code.
-
-Drop support for older Python versions if possible. Python 2.5
-introduced a lot of useful syntax and libraries which have become idiomatic
-in Python 3. Python 2.6 introduced future statements which makes
-compatibility much easier if you are going from Python 2 to 3.
-Python 2.7 continues the trend in the stdlib. Choose the newest version
-of Python which you believe can be your minimum support version
-and work from there.
-
-Target the newest version of Python 3 that you can. Beyond just the usual
-bugfixes, compatibility has continued to improve between Python 2 and 3 as time
-has passed. E.g. Python 3.3 added back the ``u`` prefix for
-strings, making source-compatible Python code easier to write.
-
-
-Writing Source-Compatible Python 2/3 Code
-=========================================
-
-Over the years the Python community has discovered that the easiest way to
-support both Python 2 and 3 in parallel is to write Python code that works in
-either version. While this might sound counter-intuitive at first, it actually
-is not difficult and typically only requires following some select
-(non-idiomatic) practices and using some key projects to help make bridging
-between Python 2 and 3 easier.
-
-Projects to Consider
---------------------
-
-The lowest level library for supporting Python 2 & 3 simultaneously is six_.
-Reading through its documentation will give you an idea of where exactly the
-Python language changed between versions 2 & 3 and thus what you will want the
-library to help you continue to support.
-
-To help automate porting your code over to using six, you can use
-modernize_. This project will attempt to rewrite your code to be as modern as
-possible while using six to smooth out any differences between Python 2 & 3.
-
-If you want to write your compatible code to feel more like Python 3 there is
-the future_ project. It tries to provide backports of objects from Python 3 so
-that you can use them from Python 2-compatible code, e.g. replacing the
-``bytes`` type from Python 2 with the one from Python 3.
-It also provides a translation script like modernize (its translation code is
-actually partially based on it) to help start working with a pre-existing code
-base. It is also unique in that its translation script will also port Python 3
-code backwards as well as Python 2 code forwards.
-
-
-Tips & Tricks
--------------
-
-To help with writing source-compatible code using one of the projects mentioned
-in `Projects to Consider`_, consider following the below suggestions. Some of
-them are handled by the suggested projects, so if you do use one of them then
-read their documentation first to see which suggestions below will taken care of
-for you.
-
-Support Python 2.7
-//////////////////
-
-As a first step, make sure that your project is compatible with Python 2.7.
-This is just good to do as Python 2.7 is the last release of Python 2 and thus
-will be used for a rather long time. It also allows for use of the ``-3`` flag
-to Python to help discover places in your code where compatibility might be an
-issue (the ``-3`` flag is in Python 2.6 but Python 2.7 adds more warnings).
-
-Try to Support Python 2.6 and Newer Only
-////////////////////////////////////////
-
-While not possible for all projects, if you can support Python 2.6 and newer
-**only**, your life will be much easier. Various future statements, stdlib
-additions, etc. exist only in Python 2.6 and later which greatly assist in
-supporting Python 3. But if you project must keep support for Python 2.5 then
-it is still possible to simultaneously support Python 3.
-
-Below are the benefits you gain if you only have to support Python 2.6 and
-newer. Some of these options are personal choice while others are
-**strongly** recommended (the ones that are more for personal choice are
-labeled as such).  If you continue to support older versions of Python then you
-at least need to watch out for situations that these solutions fix and handle
-them appropriately (which is where library help from e.g. six_ comes in handy).
-
-
-``from __future__ import print_function``
-'''''''''''''''''''''''''''''''''''''''''
-
-It will not only get you used to typing ``print()`` as a function instead of a
-statement, but it will also give you the various benefits the function has over
-the Python 2 statement (six_ provides a function if you support Python 2.5 or
-older).
-
-
-``from __future__ import unicode_literals``
-'''''''''''''''''''''''''''''''''''''''''''
-
-If you choose to use this future statement then all string literals in
-Python 2 will be assumed to be Unicode (as is already the case in Python 3).
-If you choose not to use this future statement then you should mark all of your
-text strings with a ``u`` prefix and only support Python 3.3 or newer. But you
-are **strongly** advised to do one or the other (six_ provides a function in
-case you don't want to use the future statement **and** you want to support
-Python 3.2 or older).
-
-
-Bytes/string literals
-'''''''''''''''''''''
-
-This is a **very** important one. Prefix Python 2 strings that
-are meant to contain bytes with a ``b`` prefix to very clearly delineate
-what is and is not a Python 3 text string (six_ provides a function to use for
-Python 2.5 compatibility).
-
-This point cannot be stressed enough: make sure you know what all of your string
-literals in Python 2 are meant to be in Python 3. Any string literal that
-should be treated as bytes should have the ``b`` prefix. Any string literal
-that should be Unicode/text in Python 2 should either have the ``u`` literal
-(supported, but ignored, in Python 3.3 and later) or you should have
-``from __future__ import unicode_literals`` at the top of the file. But the key
-point is you should know how Python 3 will treat every one one of your string
-literals and you should mark them as appropriate.
-
-There are some differences between byte literals in Python 2 and those in
-Python 3 thanks to the bytes type just being an alias to ``str`` in Python 2.
-See the `Handle Common "Gotchas"`_ section for what to watch out for.
-
-``from __future__ import absolute_import``
-''''''''''''''''''''''''''''''''''''''''''
-Discussed in more detail below, but you should use this future statement to
-prevent yourself from accidentally using implicit relative imports.
-
-
-Supporting Python 2.5 and Newer Only
-////////////////////////////////////
-
-If you are supporting Python 2.5 and newer there are still some features of
-Python that you can utilize.
-
-
-``from __future__ import absolute_import``
-''''''''''''''''''''''''''''''''''''''''''
-
-Implicit relative imports (e.g., importing ``spam.bacon`` from within
-``spam.eggs`` with the statement ``import bacon``) do not work in Python 3.
-This future statement moves away from that and allows the use of explicit
-relative imports (e.g., ``from . import bacon``).
-
-In Python 2.5 you must use
-the __future__ statement to get to use explicit relative imports and prevent
-implicit ones. In Python 2.6 explicit relative imports are available without
-the statement, but you still want the __future__ statement to prevent implicit
-relative imports. In Python 2.7 the __future__ statement is not needed. In
-other words, unless you are only supporting Python 2.7 or a version earlier
-than Python 2.5, use this __future__ statement.
-
-
-Mark all Unicode strings with a ``u`` prefix
-'''''''''''''''''''''''''''''''''''''''''''''
-
-While Python 2.6 has a ``__future__`` statement to automatically cause Python 2
-to treat all string literals as Unicode, Python 2.5 does not have that shortcut.
-This means you should go through and mark all string literals with a ``u``
-prefix to turn them explicitly into text strings where appropriate and only
-support Python 3.3 or newer. Otherwise use a project like six_ which provides a
-function to pass all text string literals through.
-
-
-Capturing the Currently Raised Exception
-''''''''''''''''''''''''''''''''''''''''
-
-In Python 2.5 and earlier the syntax to access the current exception is::
-
-   try:
-     raise Exception()
-   except Exception, exc:
-     # Current exception is 'exc'.
-     pass
-
-This syntax changed in Python 3 (and backported to Python 2.6 and later)
-to::
-
-   try:
-     raise Exception()
-   except Exception as exc:
-     # Current exception is 'exc'.
-     # In Python 3, 'exc' is restricted to the block; in Python 2.6/2.7 it will "leak".
-     pass
-
-Because of this syntax change you must change how you capture the current
-exception in Python 2.5 and earlier to::
-
-   try:
-     raise Exception()
-   except Exception:
-     import sys
-     exc = sys.exc_info()[1]
-     # Current exception is 'exc'.
-     pass
-
-You can get more information about the raised exception from
-:func:`sys.exc_info` than simply the current exception instance, but you most
-likely don't need it.
-
-.. note::
-   In Python 3, the traceback is attached to the exception instance
-   through the ``__traceback__`` attribute. If the instance is saved in
-   a local variable that persists outside of the ``except`` block, the
-   traceback will create a reference cycle with the current frame and its
-   dictionary of local variables.  This will delay reclaiming dead
-   resources until the next cyclic :term:`garbage collection` pass.
-
-   In Python 2, this problem only occurs if you save the traceback itself
-   (e.g. the third element of the tuple returned by :func:`sys.exc_info`)
-   in a variable.
-
-
-Handle Common "Gotchas"
-///////////////////////
-
-These are things to watch out for no matter what version of Python 2 you are
-supporting which are not syntactic considerations.
-
-
-``from __future__ import division``
-'''''''''''''''''''''''''''''''''''
-
-While the exact same outcome can be had by using the ``-Qnew`` argument to
-Python, using this future statement lifts the requirement that your users use
-the flag to get the expected behavior of division in Python 3
-(e.g., ``1/2 == 0.5; 1//2 == 0``).
-
-
-
-Specify when opening a file as binary
-'''''''''''''''''''''''''''''''''''''
-
+The Short Explanation
+=====================
+
+To make your project be single-source Python 2/3 compatible, the basic steps
+are:
+
+#. Update your code to drop support for Python 2.5 or older (supporting only
+   Python 2.7 is ideal)
+#. Make sure you have good test coverage (coverage.py_ can help;
+   ``pip install coverage``)
+#. Learn the differences between Python 2 & 3
+#. Use Modernize_ or Futurize_ to update your code (``pip install modernize`` or
+   ``pip install future``, respectively)
+#. Use Pylint_ to help make sure you don't regress on your Python 3 support
+   (if only supporting Python 2.7/3.4 or newer; ``pip install pylint``)
+#. Use caniusepython3_ to find out which of your dependencies are blocking your
+   use of Python 3 (``pip install caniusepython3``)
+#. Once your dependencies are no longer blocking you, use continuous integration
+   to make sure you stay compatible with Python 2 & 3 (tox_ can help test
+   against multiple versions of Python; ``pip install tox``)
+
+If you are dropping support for Python 2 entirely, then after you learn the
+differences between Python 2 & 3 you can run 2to3_ over your code and skip the
+rest of the steps outlined above.
+
+
+Details
+=======
+
+A key point about supporting Python 2 & 3 simultaneously is that you can start
+**today**! Even if your dependencies are not supporting Python 3 yet that does
+not mean you can't modernize your code **now** to support Python 3. Most changes
+required to support Python 3 lead to cleaner code using newer practices even in
+Python 2.
+
+Another key point is that modernizing your Python 2 code to also support
+Python 3 is largely automated for you. While you might have to make some API
+decisions thanks to Python 3 clarifying text data versus binary data, the
+lower-level work is now mostly done for you and thus can at least benefit from
+the automated changes immediately.
+
+Keep those key points in mind while you read on about the details of porting
+your code to support Python 2 & 3 simultaneously.
+
+
+Drop support for Python 2.5 and older (at least)
+------------------------------------------------
+
+While you can make Python 2.5 work with Python 3, it is **much** easier if you
+only have to work with Python 2.6 or newer (and easier still if you only have
+to work with Python 2.7). If dropping Python 2.5 is not an option then the six_
+project can help you support Python 2.5 & 3 simultaneously
+(``pip install six``). Do realize, though, that nearly all the projects listed
+in this HOWTO will not be available to you.
+
+If you are able to only support Python 2.6 or newer, then the required changes
+to your code should continue to look and feel like idiomatic Python code. At
+worst you will have to use a function instead of a method in some instances or
+have to import a function instead of using a built-in one, but otherwise the
+overall transformation should not feel foreign to you.
+
+But please aim for Python 2.7. Bugfixes for that version of Python will continue
+until 2020 while Python 2.6 is no longer supported. There are also some tools
+mentioned in this HOWTO which do not support Python 2.6 (e.g., Pylint_), and
+this will become more commonplace as time goes on.
+
+Make sure you specify the proper version support in your ``setup.py`` file
+--------------------------------------------------------------------------
+
+In your ``setup.py`` file you should have the proper `trove classifier`_
+specifying what versions of Python you support. As your project does not support
+Python 3 yet you should at least have
+``Programming Language :: Python :: 2 :: Only`` specified. Ideally you should
+also specify each major/minor version of Python that you do support, e.g.
+``Programming Language :: Python :: 2.7``.
+
+Have good test coverage
+-----------------------
+
+Once you have your code supporting the oldest version of Python 2 you want it
+to, you will want to make sure your test suite has good coverage. A good rule of
+thumb is that if you want to be confident enough in your test suite that any
+failures that appear after having tools rewrite your code are actual bugs in the
+tools and not in your code. If you want a number to aim for, try to get over 80%
+coverage (and don't feel bad if you can't easily get past 90%). If you
+don't already have a tool to measure test coverage then coverage.py_ is
+recommended.
+
+Learn the differences between Python 2 & 3
+-------------------------------------------
+
+Once you have your code well-tested you are ready to begin porting your code to
+Python 3! But to fully understand how your code is going to change and what
+you want to look out for while you code, you will want to learn what changes
+Python 3 makes in terms of Python 2. Typically the two best ways of doing that
+is reading the `"What's New"`_ doc for each release of Python 3 and the
+`Porting to Python 3`_ book (which is free online). There is also a handy
+`cheat sheet`_ from the Python-Future project.
+
+
+Update your code
+----------------
+
+Once you feel like you know what is different in Python 3 compared to Python 2,
+it's time to update your code! You have a choice between two tools in porting
+your code automatically: Modernize_ and Futurize_. Which tool you choose will
+depend on how much like Python 3 you want your code to be. Futurize_ does its
+best to make Python 3 idioms and practices exist in Python 2, e.g. backporting
+the ``bytes`` type from Python 3 so that you have semantic parity between the
+major versions of Python. Modernize_,
+on the other hand, is more conservative and targets a Python 2/3 subset of
+Python, relying on six_ to help provide compatibility.
+
+Regardless of which tool you choose, they will update your code to run under
+Python 3 while staying compatible with the version of Python 2 you started with.
+Depending on how conservative you want to be, you may want to run the tool over
+your test suite first and visually inspect the diff to make sure the
+transformation is accurate. After you have transformed your test suite and
+verified that all the tests still pass as expected, then you can transform your
+application code knowing that any tests which fail is a translation failure.
+
+Unfortunately the tools can't automate everything to make your code work under
+Python 3 and so there are a handful of things you will need to update manually
+to get full Python 3 support (which of these steps are necessary vary between
+the tools). Read the documentation for the tool you choose to use to see what it
+fixes by default and what it can do optionally to know what will (not) be fixed
+for you and what you may have to fix on your own (e.g. using ``io.open()`` over
+the built-in ``open()`` function is off by default in Modernize). Luckily,
+though, there are only a couple of things to watch out for which can be
+considered large issues that may be hard to debug if not watched for.
+
+Division
+++++++++
+
+In Python 3, ``5 / 2 == 2.5`` and not ``2``; all division between ``int`` values
+result in a ``float``. This change has actually been planned since Python 2.2
+which was released in 2002. Since then users have been encouraged to add
+``from __future__ import division`` to any and all files which use the ``/`` and
+``//`` operators or to be running the interpreter with the ``-Q`` flag. If you
+have not been doing this then you will need to go through your code and do two
+things:
+
+#. Add ``from __future__ import division`` to your files
+#. Update any division operator as necessary to either use ``//`` to use floor
+   division or continue using ``/`` and expect a float
+
+The reason that ``/`` isn't simply translated to ``//`` automatically is that if
+an object defines its own ``__div__`` method but not ``__floordiv__`` then your
+code would begin to fail.
+
+Text versus binary data
++++++++++++++++++++++++
+
+In Python 2 you could use the ``str`` type for both text and binary data.
+Unfortunately this confluence of two different concepts could lead to brittle
+code which sometimes worked for either kind of data, sometimes not. It also
+could lead to confusing APIs if people didn't explicitly state that something
+that accepted ``str`` accepted either text or binary data instead of one
+specific type. This complicated the situation especially for anyone supporting
+multiple languages as APIs wouldn't bother explicitly supporting ``unicode``
+when they claimed text data support.
+
+To make the distinction between text and binary data clearer and more
+pronounced, Python 3 did what most languages created in the age of the internet
+have done and made text and binary data distinct types that cannot blindly be
+mixed together (Python predates widespread access to the internet). For any code
+that only deals with text or only binary data, this separation doesn't pose an
+issue. But for code that has to deal with both, it does mean you might have to
+now care about when you are using text compared to binary data, which is why
+this cannot be entirely automated.
+
+To start, you will need to decide which APIs take text and which take binary
+(it is **highly** recommended you don't design APIs that can take both due to
+the difficulty of keeping the code working; as stated earlier it is difficult to
+do well). In Python 2 this means making sure the APIs that take text can work
+with ``unicode`` in Python 2 and those that work with binary data work with the
+``bytes`` type from Python 3 and thus a subset of ``str`` in Python 2 (which the
+``bytes`` type in Python 2 is an alias for). Usually the biggest issue is
+realizing which methods exist for which types in Python 2 & 3 simultaneously
+(for text that's ``unicode`` in Python 2 and ``str`` in Python 3, for binary
+that's ``str``/``bytes`` in Python 2 and ``bytes`` in Python 3). The following
+table lists the **unique** methods of each data type across Python 2 & 3
+(e.g., the ``decode()`` method is usable on the equivalent binary data type in
+either Python 2 or 3, but it can't be used by the text data type consistently
+between Python 2 and 3 because ``str`` in Python 3 doesn't have the method).
+
+======================== =====================
+**Text data**            **Binary data**
+------------------------ ---------------------
+__mod__ (``%`` operator)
+------------------------ ---------------------
+\                        decode
+------------------------ ---------------------
+encode
+------------------------ ---------------------
+format
+------------------------ ---------------------
+isdecimal
+------------------------ ---------------------
+isnumeric
+======================== =====================
+
+Making the distinction easier to handle can be accomplished by encoding and
+decoding between binary data and text at the edge of your code. This means that
+when you receive text in binary data, you should immediately decode it. And if
+your code needs to send text as binary data then encode it as late as possible.
+This allows your code to work with only text internally and thus eliminates
+having to keep track of what type of data you are working with.
+
+The next issue is making sure you know whether the string literals in your code
+represent text or binary data. At minimum you should add a ``b`` prefix to any
+literal that presents binary data. For text you should either use the
+``from __future__ import unicode_literals`` statement or add a ``u`` prefix to
+the text literal.
+
+As part of this dichotomy you also need to be careful about opening files.
 Unless you have been working on Windows, there is a chance you have not always
 bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
 binary reading).  Under Python 3, binary files and text files are clearly
 distinct and mutually incompatible; see the :mod:`io` module for details.
 Therefore, you **must** make a decision of whether a file will be used for
-binary access (allowing to read and/or write bytes data) or text access
-(allowing to read and/or write unicode data).
-
-Text files
-''''''''''
-
-Text files created using ``open()`` under Python 2 return byte strings,
-while under Python 3 they return unicode strings.  Depending on your porting
-strategy, this can be an issue.
-
-If you want text files to return unicode strings in Python 2, you have two
-possibilities:
-
-* Under Python 2.6 and higher, use :func:`io.open`.  Since :func:`io.open`
-  is essentially the same function in both Python 2 and Python 3, it will
-  help iron out any issues that might arise.
-
-* If pre-2.6 compatibility is needed, then you should use :func:`codecs.open`
-  instead.  This will make sure that you get back unicode strings in Python 2.
-
-Subclass ``object``
-'''''''''''''''''''
-
-New-style classes have been around since Python 2.2. You need to make sure
-you are subclassing from ``object`` to avoid odd edge cases involving method
-resolution order, etc. This continues to be totally valid in Python 3 (although
-unneeded as all classes implicitly inherit from ``object``).
-
-
-Deal With the Bytes/String Dichotomy
-''''''''''''''''''''''''''''''''''''
-
-One of the biggest issues people have when porting code to Python 3 is handling
-the bytes/string dichotomy. Because Python 2 allowed the ``str`` type to hold
-textual data, people have over the years been rather loose in their delineation
-of what ``str`` instances held text compared to bytes. In Python 3 you cannot
-be so care-free anymore and need to properly handle the difference. The key to
-handling this issue is to make sure that **every** string literal in your
-Python 2 code is either syntactically or functionally marked as either bytes or
-text data. After this is done you then need to make sure your APIs are designed
-to either handle a specific type or made to be properly polymorphic.
-
-
-Mark Up Python 2 String Literals
-********************************
-
-First thing you must do is designate every single string literal in Python 2
-as either textual or bytes data. If you are only supporting Python 2.6 or
-newer, this can be accomplished by marking bytes literals with a ``b`` prefix
-and then designating textual data with a ``u`` prefix or using the
-``unicode_literals`` future statement.
-
-If your project supports versions of Python predating 2.6, then you should use
-the six_ project and its ``b()`` function to denote bytes literals. For text
-literals you can either use six's ``u()`` function or use a ``u`` prefix.
-
-
-Decide what APIs Will Accept
-****************************
-
-In Python 2 it was very easy to accidentally create an API that accepted both
-bytes and textual data. But in Python 3, thanks to the more strict handling of
-disparate types, this loose usage of bytes and text together tends to fail.
-
-Take the dict ``{b'a': 'bytes', u'a': 'text'}`` in Python 2.6. It creates the
-dict ``{u'a': 'text'}`` since ``b'a' == u'a'``. But in Python 3 the equivalent
-dict creates ``{b'a': 'bytes', 'a': 'text'}``, i.e., no lost data. Similar
-issues can crop up when transitioning Python 2 code to Python 3.
-
-This means you need to choose what an API is going to accept and create and
-consistently stick to that API in both Python 2 and 3.
-
-
-Bytes / Unicode Comparison
-**************************
-
-In Python 3, mixing bytes and unicode is forbidden in most situations; it
-will raise a :class:`TypeError` where Python 2 would have attempted an implicit
-coercion between types.  However, there is one case where it doesn't and
-it can be very misleading::
-
-   >>> b"" == ""
-   False
-
-This is because an equality comparison is required by the language to always
-succeed (and return ``False`` for incompatible types).  However, this also
-means that code incorrectly ported to Python 3 can display buggy behaviour
-if such comparisons are silently executed.  To detect such situations,
-Python 3 has a ``-b`` flag that will display a warning::
-
-   $ python3 -b
-   >>> b"" == ""
-   __main__:1: BytesWarning: Comparison between bytes and string
-   False
-
-To turn the warning into an exception, use the ``-bb`` flag instead::
-
-   $ python3 -bb
-   >>> b"" == ""
-   Traceback (most recent call last):
-     File "<stdin>", line 1, in <module>
-   BytesWarning: Comparison between bytes and string
-
-
-Indexing bytes objects
-''''''''''''''''''''''
-
-Another potentially surprising change is the indexing behaviour of bytes
-objects in Python 3::
-
-   >>> b"xyz"[0]
-   120
-
-Indeed, Python 3 bytes objects (as well as :class:`bytearray` objects)
-are sequences of integers.  But code converted from Python 2 will often
-assume that indexing a bytestring produces another bytestring, not an
-integer.  To reconcile both behaviours, use slicing::
-
-   >>> b"xyz"[0:1]
-   b'x'
-   >>> n = 1
-   >>> b"xyz"[n:n+1]
-   b'y'
-
-The only remaining gotcha is that an out-of-bounds slice returns an empty
-bytes object instead of raising ``IndexError``:
-
-   >>> b"xyz"[3]
-   Traceback (most recent call last):
-     File "<stdin>", line 1, in <module>
-   IndexError: index out of range
-   >>> b"xyz"[3:4]
-   b''
-
-
-``__str__()``/``__unicode__()``
-'''''''''''''''''''''''''''''''
-
-In Python 2, objects can specify both a string and unicode representation of
-themselves. In Python 3, though, there is only a string representation. This
-becomes an issue as people can inadvertently do things in their ``__str__()``
-methods which have unpredictable results (e.g., infinite recursion if you
-happen to use the ``unicode(self).encode('utf8')`` idiom as the body of your
-``__str__()`` method).
-
-You can use a mixin class to work around this. This allows you to only define a
-``__unicode__()`` method for your class and let the mixin derive
-``__str__()`` for you (code from
-http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/)::
-
-   import sys
-
-   class UnicodeMixin(object):
-
-     """Mixin class to handle defining the proper __str__/__unicode__
-     methods in Python 2 or 3."""
-
-     if sys.version_info[0] >= 3: # Python 3
-         def __str__(self):
-             return self.__unicode__()
-     else:  # Python 2
-         def __str__(self):
-             return self.__unicode__().encode('utf8')
-
-
-   class Spam(UnicodeMixin):
-
-     def __unicode__(self):
-         return u'spam-spam-bacon-spam'  # 2to3 will remove the 'u' prefix
-
-
-Don't Index on Exceptions
-'''''''''''''''''''''''''
-
-In Python 2, the following worked::
-
-   >>> exc = Exception(1, 2, 3)
-   >>> exc.args[1]
-   2
-   >>> exc[1]  # Python 2 only!
-   2
-
-But in Python 3, indexing directly on an exception is an error. You need to
-make sure to only index on the :attr:`BaseException.args` attribute which is a
-sequence containing all arguments passed to the :meth:`__init__` method.
-
-Even better is to use the documented attributes the exception provides.
-
-
-Don't use ``__getslice__`` & Friends
-''''''''''''''''''''''''''''''''''''
-
-Been deprecated for a while, but Python 3 finally drops support for
-``__getslice__()``, etc. Move completely over to :meth:`__getitem__` and
-friends.
-
-
-Updating doctests
-'''''''''''''''''
-
-Don't forget to make them Python 2/3 compatible as well. If you wrote a
-monolithic set of doctests (e.g., a single docstring containing all of your
-doctests), you should at least consider breaking the doctests up into smaller
-pieces to make it more manageable to fix. Otherwise it might very well be worth
-your time and effort to port your tests to :mod:`unittest`.
-
-
-Update ``map`` for imbalanced input sequences
-'''''''''''''''''''''''''''''''''''''''''''''
-
-With Python 2, when ``map`` was given more than one input sequence it would pad
-the shorter sequences with ``None`` values, returning a sequence as long as the
-longest input sequence.
-
-With Python 3, if the input sequences to ``map`` are of unequal length, ``map``
-will stop at the termination of the shortest of the sequences. For full
-compatibility with ``map`` from Python 2.x, wrap the sequence arguments in
-:func:`itertools.zip_longest`, e.g. ``map(func, *sequences)`` becomes
-``list(map(func, itertools.zip_longest(*sequences)))``.
-
-Eliminate ``-3`` Warnings
--------------------------
-
-When you run your application's test suite, run it using the ``-3`` flag passed
-to Python. This will cause various warnings to be raised during execution about
-things that are semantic changes between Python 2 and 3. Try to eliminate those
-warnings to make your code even more portable to Python 3.
-
-
-Alternative Approaches
-======================
-
-While supporting Python 2 & 3 simultaneously is typically the preferred choice
-by people so that they can continue to improve code and have it work for the
-most number of users, your life may be easier if you only have to support one
-major version of Python going forward.
-
-Supporting Only Python 3 Going Forward From Python 2 Code
----------------------------------------------------------
-
-If you have Python 2 code but going forward only want to improve it as Python 3
-code, then you can use :ref:`2to3 <2to3-reference>` to translate your Python 2
-code to Python 3 code.  This is only recommended, though, if your current
-version of your project is going into maintenance mode and you want all new features to be exclusive to Python 3.
-
-
-Backporting Python 3 code to Python 2
--------------------------------------
-
-If you have Python 3 code and have little interest in supporting Python 2 you
-can use 3to2_ to translate from Python 3 code to Python 2 code. This is only
-recommended if you don't plan to heavily support Python 2 users. Otherwise
-write your code for Python 3 and then backport as far back as you want. This
-is typically easier than going from Python 2 to 3 as you will have worked out
-any difficulties with e.g. bytes/strings, etc.
-
-
-Other Resources
-===============
-
-The authors of the following blog posts, wiki pages, and books deserve special
-thanks for making public their tips for porting Python 2 code to Python 3 (and
-thus helping provide information for this document and its various revisions
-over the years):
-
-* https://wiki.python.org/moin/PortingPythonToPy3k
-* http://python3porting.com/
-* http://docs.pythonsprints.com/python3_porting/py-porting.html
-* http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/
-* http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html
-* http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
-* http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/
-* https://wiki.ubuntu.com/Python/3
-
-If you feel there is something missing from this document that should be added,
-please email the python-porting_ mailing list.
-
-
-.. _3to2: https://pypi.python.org/pypi/3to2
-.. _Cheeseshop: PyPI_
-.. _coverage: https://pypi.python.org/pypi/coverage
-.. _future: http://python-future.org/
-.. _modernize: https://github.com/mitsuhiko/python-modernize
+binary access (allowing to read and/or write binary data) or text access
+(allowing to read and/or write text data). You should also use :func:`io.open`
+for opening files instead of the built-in :func:`open` function as the :mod:`io`
+module is consistent from Python 2 to 3 while the built-in :func:`open` function
+is not (in Python 3 it's actually :func:`io.open`).
+
+The constructors of both ``str`` and ``bytes`` have different semantics for the
+same arguments between Python 2 & 3. Passing an integer to ``bytes`` in Python 2
+will give you the string representation of the integer: ``bytes(3) == '3'``.
+But in Python 3, an integer argument to ``bytes`` will give you a bytes object
+as long as the integer specified, filled with null bytes:
+``bytes(3) == b'\x00\x00\x00'``. A similar worry is necessary when passing a
+bytes object to ``str``. In Python 2 you just get the bytes object back:
+``str(b'3') == b'3'``. But in Python 3 you get the string representation of the
+bytes object: ``str(b'3') == "b'3'"``.
+
+Finally, the indexing of binary data requires careful handling (slicing does
+**not** require any special handling). In Python 2,
+``b'123'[1] == b'2'`` while in Python 3 ``b'123'[1] == 50``. Because binary data
+is simply a collection of binary numbers, Python 3 returns the integer value for
+the byte you index on. But in Python 2 because ``bytes == str``, indexing
+returns a one-item slice of bytes. The six_ project has a function
+named ``six.indexbytes()`` which will return an integer like in Python 3:
+``six.indexbytes(b'123', 1)``.
+
+To summarize:
+
+#. Decide which of your APIs take text and which take binary data
+#. Make sure that your code that works with text also works with ``unicode`` and
+   code for binary data works with ``bytes`` in Python 2 (see the table above
+   for what methods you cannot use for each type)
+#. Mark all binary literals with a ``b`` prefix, use a ``u`` prefix or
+   :mod:`__future__` import statement for text literals
+#. Decode binary data to text as soon as possible, encode text as binary data as
+   late as possible
+#. Open files using :func:`io.open` and make sure to specify the ``b`` mode when
+   appropriate
+#. Be careful when indexing binary data
+
+Prevent compatibility regressions
+---------------------------------
+
+Once you have fully translated your code to be compatible with Python 3, you
+will want to make sure your code doesn't regress and stop working under
+Python 3. This is especially true if you have a dependency which is blocking you
+from actually running under Python 3 at the moment.
+
+To help with staying compatible, any new modules you create should have
+at least the following block of code at the top of it::
+
+    from __future__ import absolute_import
+    from __future__ import division
+    from __future__ import print_function
+    from __future__ import unicode_literals
+
+You can also run Python 2 with the ``-3`` flag to be warned about various
+compatibility issues your code triggers during execution. If you turn warnings
+into errors with ``-Werror`` then you can make sure that you don't accidentally
+miss a warning.
+
+
+You can also use the Pylint_ project and its ``--py3k`` flag to lint your code
+to receive warnings when your code begins to deviate from Python 3
+compatibility. This also prevents you from having to run Modernize_ or Futurize_
+over your code regularly to catch compatibility regressions. This does require
+you only support Python 2.7 and Python 3.4 or newer as that is Pylint's
+minimum Python version support.
+
+
+Check which dependencies block your transition
+----------------------------------------------
+
+**After** you have made your code compatible with Python 3 you should begin to
+care about whether your dependencies have also been ported. The caniusepython3_
+project was created to help you determine which projects
+-- directly or indirectly -- are blocking you from supporting Python 3. There
+is both a command-line tool as well as a web interface at
+https://caniusepython3.com .
+
+The project also provides code which you can integrate into your test suite so
+that you will have a failing test when you no longer have dependencies blocking
+you from using Python 3. This allows you to avoid having to manually check your
+dependencies and to be notified quickly when you can start running on Python 3.
+
+Update your ``setup.py`` file to denote Python 3 compatibility
+--------------------------------------------------------------
+
+Once your code works under Python 3, you should update the classifiers in
+your ``setup.py`` to contain ``Programming Language :: Python :: 3`` and to not
+specify sole Python 2 support. This will tell
+anyone using your code that you support Python 2 **and** 3. Ideally you will
+also want to add classifiers for each major/minor version of Python you now
+support.
+
+Use continuous integration to stay compatible
+---------------------------------------------
+
+Once you are able to fully run under Python 3 you will want to make sure your
+code always works under both Python 2 & 3. Probably the best tool for running
+your tests under multiple Python interpreters is tox_. You can then integrate
+tox with your continuous integration system so that you never accidentally break
+Python 2 or 3 support.
+
+You may also want to use use the ``-bb`` flag with the Python 3 interpreter to
+trigger an exception when you are comparing bytes to strings. Usually it's
+simply ``False``, but if you made a mistake in your separation of text/binary
+data handling you may be accidentally comparing text and binary data. This flag
+will raise an exception when that occurs to help track down such cases.
+
+And that's mostly it! At this point your code base is compatible with both
+Python 2 and 3 simultaneously. Your testing will also be set up so that you
+don't accidentally break Python 2 or 3 compatibility regardless of which version
+you typically run your tests under while developing.
+
+
+Dropping Python 2 support completely
+====================================
+
+If you are able to fully drop support for Python 2, then the steps required
+to transition to Python 3 simplify greatly.
+
+#. Update your code to only support Python 2.7
+#. Make sure you have good test coverage (coverage.py_ can help)
+#. Learn the differences between Python 2 & 3
+#. Use 2to3_ to rewrite your code to run only under Python 3
+
+After this your code will be fully Python 3 compliant but in a way that is not
+supported by Python 2. You should also update the classifiers in your
+``setup.py`` to contain ``Programming Language :: Python :: 3 :: Only``.
+
+
+.. _2to3: https://docs.python.org/3/library/2to3.html
+.. _caniusepython3: https://pypi.python.org/pypi/caniusepython3
+.. _cheat sheet: http://python-future.org/compatible_idioms.html
+.. _coverage.py: https://pypi.python.org/pypi/coverage
+.. _Futurize: http://python-future.org/automatic_conversion.html
+.. _Modernize: http://python-modernize.readthedocs.org/en/latest/
 .. _Porting to Python 3: http://python3porting.com/
-.. _PyPI: https://pypi.python.org/pypi
-.. _Python 3 Packages: https://pypi.python.org/pypi?:action=browse&c=533&show=all
+.. _Pylint: https://pypi.python.org/pypi/pylint
 .. _Python 3 Q & A: http://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html
+
+.. _python-future: http://python-future.org/
 .. _python-porting: https://mail.python.org/mailman/listinfo/python-porting
 .. _six: https://pypi.python.org/pypi/six
 .. _tox: https://pypi.python.org/pypi/tox
-.. _trove classifiers: https://pypi.python.org/pypi?%3Aaction=list_classifiers
+.. _trove classifier: https://pypi.python.org/pypi?%3Aaction=list_classifiers
+.. _"What's New": https://docs.python.org/3/whatsnew/index.html
index 407a920..8138a09 100644 (file)
@@ -32,8 +32,8 @@ For a while people just wrote programs that didn't display accents.  I remember
 looking at Apple ][ BASIC programs, published in French-language publications in
 the mid-1980s, that had lines like these::
 
-   PRINT "FICHIER EST COMPLETE."
-   PRINT "CARACTERE NON ACCEPTE."
+   PRINT "MISE A JOUR TERMINEE"
+   PRINT "PARAMETRES ENREGISTRES"
 
 Those messages should contain accents, and they just look wrong to someone who
 can read French.
index 6534753..d8a0562 100644 (file)
@@ -732,6 +732,4 @@ found in the Python wiki.
    <https://wiki.python.org/moin/WebFrameworks>`_.
 
    Most frameworks also have their own mailing lists and IRC channels, look out
-   for these on the projects' web sites.  There is also a general "Python in the
-   Web" IRC channel on freenode called `#python.web
-   <https://wiki.python.org/moin/PoundPythonWeb>`_.
+   for these on the projects' web sites.
index 25005ee..9955646 100644 (file)
@@ -1216,8 +1216,8 @@ Action classes implement the Action API, a callable which returns a callable
 which processes arguments from the command-line. Any object which follows this
 API may be passed as the ``action`` parameter to :meth:`add_argument`.
 
-.. class:: Action(option_strings, dest, nargs=None, const=None, default=None,
-                  type=None, choices=None, required=False, help=None,
+.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
+                  type=None, choices=None, required=False, help=None, \
                   metavar=None)
 
 Action objects are used by an ArgumentParser to represent the information needed
@@ -1499,12 +1499,15 @@ Sub-commands
    * parser_class - class which will be used to create sub-parser instances, by
      default the class of the current parser (e.g. ArgumentParser)
 
-   * dest - name of the attribute under which sub-command name will be
+   * action_ - the basic type of action to be taken when this argument is
+     encountered at the command line
+
+   * dest_ - name of the attribute under which sub-command name will be
      stored; by default None and no value is stored
 
-   * help - help for sub-parser group in help output, by default None
+   * help_ - help for sub-parser group in help output, by default None
 
-   * metavar - string presenting available sub-commands in help; by default it
+   * metavar_ - string presenting available sub-commands in help; by default it
      is None and presents sub-commands in form {cmd1, cmd2, ..}
 
    Some example usage::
@@ -1881,10 +1884,7 @@ Customizing file parsing
    as an argument::
 
     def convert_arg_line_to_args(self, arg_line):
-        for arg in arg_line.split():
-            if not arg.strip():
-                continue
-            yield arg
+        return arg_line.split()
 
 
 Exiting methods
index 5cbb426..0a05686 100644 (file)
@@ -161,13 +161,13 @@ Hyperbolic functions
 
 .. function:: acosh(x)
 
-   Return the hyperbolic arc cosine of *x*. There is one branch cut, extending left
-   from 1 along the real axis to -∞, continuous from above.
+   Return the inverse hyperbolic cosine of *x*. There is one branch cut,
+   extending left from 1 along the real axis to -∞, continuous from above.
 
 
 .. function:: asinh(x)
 
-   Return the hyperbolic arc sine of *x*. There are two branch cuts:
+   Return the inverse hyperbolic sine of *x*. There are two branch cuts:
    One extends from ``1j`` along the imaginary axis to ``∞j``,
    continuous from the right.  The other extends from ``-1j`` along
    the imaginary axis to ``-∞j``, continuous from the left.
@@ -178,7 +178,7 @@ Hyperbolic functions
 
 .. function:: atanh(x)
 
-   Return the hyperbolic arc tangent of *x*. There are two branch cuts: One
+   Return the inverse hyperbolic tangent of *x*. There are two branch cuts: One
    extends from ``1`` along the real axis to ``∞``, continuous from below. The
    other extends from ``-1`` along the real axis to ``-∞``, continuous from
    above.
index 05c7156..feeb236 100644 (file)
@@ -787,7 +787,7 @@ methods and attributes from the underlying stream.
 Encodings and Unicode
 ---------------------
 
-Unicode strings are stored internally as sequences of codepoints (to be precise
+Unicode strings are stored internally as sequences of code points (to be precise
 as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
 via ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, with the
 former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data
@@ -796,24 +796,24 @@ and how these arrays are stored as bytes become an issue.  Transforming a
 unicode object into a sequence of bytes is called encoding and recreating the
 unicode object from the sequence of bytes is known as decoding.  There are many
 different methods for how this transformation can be done (these methods are
-also called encodings). The simplest method is to map the codepoints 0-255 to
+also called encodings). The simplest method is to map the code points 0-255 to
 the bytes ``0x0``-``0xff``. This means that a unicode object that contains
-codepoints above ``U+00FF`` can't be encoded with this method (which is called
+code points above ``U+00FF`` can't be encoded with this method (which is called
 ``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
 :exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
 codec can't encode character u'\u1234' in position 3: ordinal not in
 range(256)``.
 
 There's another group of encodings (the so called charmap encodings) that choose
-a different subset of all unicode code points and how these codepoints are
+a different subset of all unicode code points and how these code points are
 mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
 e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
 Windows). There's a string constant with 256 characters that shows you which
 character is mapped to which byte value.
 
-All of these encodings can only encode 256 of the 1114112 codepoints
+All of these encodings can only encode 256 of the 1114112 code points
 defined in unicode. A simple and straightforward way that can store each Unicode
-code point, is to store each codepoint as four consecutive bytes. There are two
+code point, is to store each code point as four consecutive bytes. There are two
 possibilities: store the bytes in big endian or in little endian order. These
 two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
 disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
index 3d8ef77..b8cb530 100644 (file)
@@ -14,7 +14,7 @@
    module: cPickle
    module: copy
 
-The :mod:`copy_reg` module offers a way to define fuctions used while pickling
+The :mod:`copy_reg` module offers a way to define functions used while pickling
 specific objects.  The :mod:`pickle`, :mod:`cPickle`, and :mod:`copy` modules
 use those functions when pickling/copying those objects.  The module provides
 configuration information about object constructors which are not classes.
index 4276e91..0cc36e9 100644 (file)
@@ -619,8 +619,8 @@ Example of working with :class:`date`:
 
 .. _datetime-datetime:
 
-:class:`datetime` Objects
--------------------------
+:class:`.datetime` Objects
+--------------------------
 
 A :class:`.datetime` object is a single object containing all the information
 from a :class:`date` object and a :class:`.time` object.  Like a :class:`date`
index d5ba4f0..564d10c 100644 (file)
@@ -236,7 +236,7 @@ For more advanced work, it may be useful to create alternate contexts using the
 Context() constructor.  To make an alternate active, use the :func:`setcontext`
 function.
 
-In accordance with the standard, the :mod:`Decimal` module provides two ready to
+In accordance with the standard, the :mod:`decimal` module provides two ready to
 use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
 former is especially useful for debugging because many of the traps are
 enabled:
index c9f5e6b..727af41 100644 (file)
@@ -9,9 +9,9 @@
 --------------
 
 The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
-disassembling it. The CPython bytecode which this module takes as an
-input is defined in the file :file:`Include/opcode.h` and used by the compiler
-and the interpreter.
+disassembling it. The CPython bytecode which this module takes as an input is
+defined in the file :file:`Include/opcode.h` and used by the compiler and the
+interpreter.
 
 .. impl-detail::
 
@@ -40,17 +40,18 @@ The :mod:`dis` module defines the following functions and constants:
 
 .. function:: dis([bytesource])
 
-   Disassemble the *bytesource* object. *bytesource* can denote either a module, a
-   class, a method, a function, or a code object.   For a module, it disassembles
-   all functions.  For a class, it disassembles all methods.  For a single code
-   sequence, it prints one line per bytecode instruction.  If no object is
-   provided, it disassembles the last traceback.
+   Disassemble the *bytesource* object. *bytesource* can denote either a module,
+   a class, a method, a function, or a code object.  For a module, it
+   disassembles all functions.  For a class, it disassembles all methods.  For a
+   single code sequence, it prints one line per bytecode instruction.  If no
+   object is provided, it disassembles the last traceback.
 
 
 .. function:: distb([tb])
 
-   Disassembles the top-of-stack function of a traceback, using the last traceback
-   if none was passed.  The instruction causing the exception is indicated.
+   Disassembles the top-of-stack function of a traceback, using the last
+   traceback if none was passed.  The instruction causing the exception is
+   indicated.
 
 
 .. function:: disassemble(code[, lasti])
@@ -233,8 +234,8 @@ result back on the stack.
 
 .. opcode:: BINARY_DIVIDE ()
 
-   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is not
-   in effect.
+   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is
+   not in effect.
 
 
 .. opcode:: BINARY_FLOOR_DIVIDE ()
@@ -244,8 +245,8 @@ result back on the stack.
 
 .. opcode:: BINARY_TRUE_DIVIDE ()
 
-   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is in
-   effect.
+   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is
+   in effect.
 
 
 .. opcode:: BINARY_MODULO ()
@@ -445,32 +446,32 @@ Miscellaneous opcodes.
 .. opcode:: PRINT_EXPR ()
 
    Implements the expression statement for the interactive mode.  TOS is removed
-   from the stack and printed.  In non-interactive mode, an expression statement is
-   terminated with :opcode:`POP_TOP`.
+   from the stack and printed.  In non-interactive mode, an expression statement
+   is terminated with :opcode:`POP_TOP`.
 
 
 .. opcode:: PRINT_ITEM ()
 
-   Prints TOS to the file-like object bound to ``sys.stdout``.  There is one such
-   instruction for each item in the :keyword:`print` statement.
+   Prints TOS to the file-like object bound to ``sys.stdout``.  There is one
+   such instruction for each item in the :keyword:`print` statement.
 
 
 .. opcode:: PRINT_ITEM_TO ()
 
-   Like ``PRINT_ITEM``, but prints the item second from TOS to the file-like object
-   at TOS.  This is used by the extended print statement.
+   Like ``PRINT_ITEM``, but prints the item second from TOS to the file-like
+   object at TOS.  This is used by the extended print statement.
 
 
 .. opcode:: PRINT_NEWLINE ()
 
-   Prints a new line on ``sys.stdout``.  This is generated as the last operation of
-   a :keyword:`print` statement, unless the statement ends with a comma.
+   Prints a new line on ``sys.stdout``.  This is generated as the last operation
+   of a :keyword:`print` statement, unless the statement ends with a comma.
 
 
 .. opcode:: PRINT_NEWLINE_TO ()
 
-   Like ``PRINT_NEWLINE``, but prints the new line on the file-like object on the
-   TOS.  This is used by the extended print statement.
+   Like ``PRINT_NEWLINE``, but prints the new line on the file-like object on
+   the TOS.  This is used by the extended print statement.
 
 
 .. opcode:: BREAK_LOOP ()
@@ -487,15 +488,15 @@ Miscellaneous opcodes.
 .. opcode:: LIST_APPEND (i)
 
    Calls ``list.append(TOS[-i], TOS)``.  Used to implement list comprehensions.
-   While the appended value is popped off, the list object remains on the
-   stack so that it is available for further iterations of the loop.
+   While the appended value is popped off, the list object remains on the stack
+   so that it is available for further iterations of the loop.
 
 
 .. opcode:: LOAD_LOCALS ()
 
-   Pushes a reference to the locals of the current scope on the stack. This is used
-   in the code for a class definition: After the class body is evaluated, the
-   locals are passed to the class definition.
+   Pushes a reference to the locals of the current scope on the stack. This is
+   used in the code for a class definition: After the class body is evaluated,
+   the locals are passed to the class definition.
 
 
 .. opcode:: RETURN_VALUE ()
@@ -510,9 +511,9 @@ Miscellaneous opcodes.
 
 .. opcode:: IMPORT_STAR ()
 
-   Loads all symbols not starting with ``'_'`` directly from the module TOS to the
-   local namespace. The module is popped after loading all names. This opcode
-   implements ``from module import *``.
+   Loads all symbols not starting with ``'_'`` directly from the module TOS to
+   the local namespace. The module is popped after loading all names. This
+   opcode implements ``from module import *``.
 
 
 .. opcode:: EXEC_STMT ()
@@ -523,8 +524,8 @@ Miscellaneous opcodes.
 
 .. opcode:: POP_BLOCK ()
 
-   Removes one block from the block stack.  Per frame, there is a  stack of blocks,
-   denoting nested loops, try statements, and such.
+   Removes one block from the block stack.  Per frame, there is a stack of
+   blocks, denoting nested loops, try statements, and such.
 
 
 .. opcode:: END_FINALLY ()
@@ -600,8 +601,8 @@ the more significant byte last.
 
 .. opcode:: DUP_TOPX (count)
 
-   Duplicate *count* items, keeping them in the same order. Due to implementation
-   limits, *count* should be between 1 and 5 inclusive.
+   Duplicate *count* items, keeping them in the same order. Due to
+   implementation limits, *count* should be between 1 and 5 inclusive.
 
 
 .. opcode:: STORE_ATTR (namei)
@@ -637,8 +638,8 @@ the more significant byte last.
 
 .. opcode:: BUILD_TUPLE (count)
 
-   Creates a tuple consuming *count* items from the stack, and pushes the resulting
-   tuple onto the stack.
+   Creates a tuple consuming *count* items from the stack, and pushes the
+   resulting tuple onto the stack.
 
 
 .. opcode:: BUILD_LIST (count)
@@ -667,9 +668,9 @@ the more significant byte last.
 
    Imports the module ``co_names[namei]``.  TOS and TOS1 are popped and provide
    the *fromlist* and *level* arguments of :func:`__import__`.  The module
-   object is pushed onto the stack.  The current namespace is not affected:
-   for a proper import statement, a subsequent ``STORE_FAST`` instruction
-   modifies the namespace.
+   object is pushed onto the stack.  The current namespace is not affected: for
+   a proper import statement, a subsequent ``STORE_FAST`` instruction modifies
+   the namespace.
 
 
 .. opcode:: IMPORT_FROM (namei)
@@ -696,14 +697,14 @@ the more significant byte last.
 
 .. opcode:: JUMP_IF_TRUE_OR_POP (target)
 
-   If TOS is true, sets the bytecode counter to *target* and leaves TOS
-   on the stack.  Otherwise (TOS is false), TOS is popped.
+   If TOS is true, sets the bytecode counter to *target* and leaves TOS on the
+   stack.  Otherwise (TOS is false), TOS is popped.
 
 
 .. opcode:: JUMP_IF_FALSE_OR_POP (target)
 
-   If TOS is false, sets the bytecode counter to *target* and leaves
-   TOS on the stack.  Otherwise (TOS is true), TOS is popped.
+   If TOS is false, sets the bytecode counter to *target* and leaves TOS on the
+   stack.  Otherwise (TOS is true), TOS is popped.
 
 
 .. opcode:: JUMP_ABSOLUTE (target)
@@ -732,19 +733,19 @@ the more significant byte last.
 
 .. opcode:: SETUP_EXCEPT (delta)
 
-   Pushes a try block from a try-except clause onto the block stack. *delta* points
-   to the first except block.
+   Pushes a try block from a try-except clause onto the block stack. *delta*
+   points to the first except block.
 
 
 .. opcode:: SETUP_FINALLY (delta)
 
-   Pushes a try block from a try-except clause onto the block stack. *delta* points
-   to the finally block.
+   Pushes a try block from a try-except clause onto the block stack. *delta*
+   points to the finally block.
 
 .. opcode:: STORE_MAP ()
 
-   Store a key and value pair in a dictionary.  Pops the key and value while leaving
-   the dictionary on the stack.
+   Store a key and value pair in a dictionary.  Pops the key and value while
+   leaving the dictionary on the stack.
 
 .. opcode:: LOAD_FAST (var_num)
 
@@ -764,8 +765,8 @@ the more significant byte last.
 .. opcode:: LOAD_CLOSURE (i)
 
    Pushes a reference to the cell contained in slot *i* of the cell and free
-   variable storage.  The name of the variable is  ``co_cellvars[i]`` if *i* is
-   less than the length of *co_cellvars*.  Otherwise it is  ``co_freevars[i -
+   variable storage.  The name of the variable is ``co_cellvars[i]`` if *i* is
+   less than the length of *co_cellvars*.  Otherwise it is ``co_freevars[i -
    len(co_cellvars)]``.
 
 
@@ -797,18 +798,19 @@ the more significant byte last.
 
    Calls a function.  The low byte of *argc* indicates the number of positional
    parameters, the high byte the number of keyword parameters. On the stack, the
-   opcode finds the keyword parameters first.  For each keyword argument, the value
-   is on top of the key.  Below the keyword parameters, the positional parameters
-   are on the stack, with the right-most parameter on top.  Below the parameters,
-   the function object to call is on the stack.  Pops all function arguments, and
-   the function itself off the stack, and pushes the return value.
+   opcode finds the keyword parameters first.  For each keyword argument, the
+   value is on top of the key.  Below the keyword parameters, the positional
+   parameters are on the stack, with the right-most parameter on top.  Below the
+   parameters, the function object to call is on the stack.  Pops all function
+   arguments, and the function itself off the stack, and pushes the return
+   value.
 
 
 .. opcode:: MAKE_FUNCTION (argc)
 
-   Pushes a new function object on the stack.  TOS is the code associated with the
-   function.  The function object is defined to have *argc* default parameters,
-   which are found below TOS.
+   Pushes a new function object on the stack.  TOS is the code associated with
+   the function.  The function object is defined to have *argc* default
+   parameters, which are found below TOS.
 
 
 .. opcode:: MAKE_CLOSURE (argc)
@@ -832,34 +834,34 @@ the more significant byte last.
 
    Prefixes any opcode which has an argument too big to fit into the default two
    bytes.  *ext* holds two additional bytes which, taken together with the
-   subsequent opcode's argument, comprise a four-byte argument, *ext* being the two
-   most-significant bytes.
+   subsequent opcode's argument, comprise a four-byte argument, *ext* being the
+   two most-significant bytes.
 
 
 .. opcode:: CALL_FUNCTION_VAR (argc)
 
-   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The top element
-   on the stack contains the variable argument list, followed by keyword and
-   positional arguments.
+   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The
+   top element on the stack contains the variable argument list, followed by
+   keyword and positional arguments.
 
 
 .. opcode:: CALL_FUNCTION_KW (argc)
 
-   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The top element
-   on the stack contains the keyword arguments dictionary,  followed by explicit
-   keyword and positional arguments.
+   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`. The
+   top element on the stack contains the keyword arguments dictionary, followed
+   by explicit keyword and positional arguments.
 
 
 .. opcode:: CALL_FUNCTION_VAR_KW (argc)
 
-   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`.  The top
-   element on the stack contains the keyword arguments dictionary, followed by the
-   variable-arguments tuple, followed by explicit keyword and positional arguments.
+   Calls a function. *argc* is interpreted as in :opcode:`CALL_FUNCTION`.  The
+   top element on the stack contains the keyword arguments dictionary, followed
+   by the variable-arguments tuple, followed by explicit keyword and positional
+   arguments.
 
 
 .. opcode:: HAVE_ARGUMENT ()
 
-   This is not really an opcode.  It identifies the dividing line between opcodes
-   which don't take arguments ``< HAVE_ARGUMENT`` and those which do ``>=
-   HAVE_ARGUMENT``.
-
+   This is not really an opcode.  It identifies the dividing line between
+   opcodes which don't take arguments ``< HAVE_ARGUMENT`` and those which do
+   ``>= HAVE_ARGUMENT``.
index b14c551..a539654 100644 (file)
@@ -85,7 +85,7 @@ patterns.
       >>>
       >>> regex = fnmatch.translate('*.txt')
       >>> regex
-      '.*\\.txt$'
+      '.*\\.txt\\Z(?ms)'
       >>> reobj = re.compile(regex)
       >>> reobj.match('foobar.txt')
       <_sre.SRE_Match object at 0x...>
index b42cf64..2d85de1 100644 (file)
@@ -55,18 +55,26 @@ The module defines the following items:
       *timeout* was added.
 
 
-.. class:: FTP_TLS([host[, user[, passwd[, acct[, keyfile[, certfile[, timeout]]]]]]])
+.. class:: FTP_TLS([host[, user[, passwd[, acct[, keyfile[, certfile[, context[, timeout]]]]]]]])
 
    A :class:`FTP` subclass which adds TLS support to FTP as described in
    :rfc:`4217`.
    Connect as usual to port 21 implicitly securing the FTP control connection
    before authenticating. Securing the data connection requires the user to
-   explicitly ask for it by calling the :meth:`prot_p` method.
-   *keyfile* and *certfile* are optional -- they can contain a PEM formatted
-   private key and certificate chain file name for the SSL connection.
+   explicitly ask for it by calling the :meth:`prot_p` method.  *context*
+   is a :class:`ssl.SSLContext` object which allows bundling SSL configuration
+   options, certificates and private keys into a single (potentially
+   long-lived) structure.  Please read :ref:`ssl-security` for best practices.
+
+   *keyfile* and *certfile* are a legacy alternative to *context* -- they
+   can point to PEM-formatted private key and certificate chain files
+   (respectively) for the SSL connection.
 
    .. versionadded:: 2.7
 
+   .. versionchanged:: 2.7.10
+      The *context* parameter was added.
+
    Here's a sample session using the :class:`FTP_TLS` class:
 
    >>> from ftplib import FTP_TLS
@@ -384,7 +392,7 @@ FTP_TLS Objects
 
 .. attribute:: FTP_TLS.ssl_version
 
-   The SSL version to use (defaults to *TLSv1*).
+   The SSL version to use (defaults to :attr:`ssl.PROTOCOL_SSLv23`).
 
 .. method:: FTP_TLS.auth()
 
index 99ba882..8af9f58 100644 (file)
@@ -22,12 +22,17 @@ available.  They are listed here in alphabetical order.
 :func:`classmethod`  :func:`getattr`    :func:`map`         |func-repr|_       :func:`xrange`
 :func:`cmp`          :func:`globals`    :func:`max`         :func:`reversed`   :func:`zip`
 :func:`compile`      :func:`hasattr`    |func-memoryview|_  :func:`round`      :func:`__import__`
-:func:`complex`      :func:`hash`       :func:`min`         |func-set|_        :func:`apply`
-:func:`delattr`      :func:`help`       :func:`next`        :func:`setattr`    :func:`buffer`
-|func-dict|_         :func:`hex`        :func:`object`      :func:`slice`      :func:`coerce`
-:func:`dir`          :func:`id`         :func:`oct`         :func:`sorted`     :func:`intern`
+:func:`complex`      :func:`hash`       :func:`min`         |func-set|_        ..
+:func:`delattr`      :func:`help`       :func:`next`        :func:`setattr`    ..
+|func-dict|_         :func:`hex`        :func:`object`      :func:`slice`      ..
+:func:`dir`          :func:`id`         :func:`oct`         :func:`sorted`     ..
 ===================  =================  ==================  =================  ====================
 
+In addition, there are other four built-in functions that are no longer
+considered essential: :func:`apply`, :func:`buffer`, :func:`coerce`, and
+:func:`intern`.  They are documented in the :ref:`non-essential-built-in-funcs`
+section.
+
 .. using :func:`dict` would create a link to another page, so local targets are
    used, with replacement texts to make the output in the table consistent
 
@@ -1173,12 +1178,6 @@ available.  They are listed here in alphabetical order.
 
    There are a number of other caveats:
 
-   If a module is syntactically correct but its initialization fails, the first
-   :keyword:`import` statement for it does not bind its name locally, but does
-   store a (partially initialized) module object in ``sys.modules``.  To reload the
-   module you must first :keyword:`import` it again (this will bind the name to the
-   partially initialized module object) before you can :func:`reload` it.
-
    When a module is reloaded, its dictionary (containing the module's global
    variables) is retained.  Redefinitions of names will override the old
    definitions, so this is generally not a problem.  If the new version of a module
index 617e3fe..a7d1f45 100644 (file)
@@ -49,7 +49,8 @@ The following functions are provided:
 .. function:: heappop(heap)
 
    Pop and return the smallest item from the *heap*, maintaining the heap
-   invariant.  If the heap is empty, :exc:`IndexError` is raised.
+   invariant.  If the heap is empty, :exc:`IndexError` is raised.  To access the
+   smallest item without popping it, use ``heap[0]``.
 
 .. function:: heappushpop(heap, item)
 
@@ -125,7 +126,8 @@ The module also offers three general purpose functions based on heaps.
 The latter two functions perform best for smaller values of *n*.  For larger
 values, it is more efficient to use the :func:`sorted` function.  Also, when
 ``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
-functions.
+functions.  If repeated usage of these functions is required, consider turning
+the iterable into an actual heap.
 
 
 Basic Examples
@@ -274,11 +276,11 @@ However, there are other representations which are more efficient overall, yet
 the worst cases might be terrible.
 
 Heaps are also very useful in big disk sorts.  You most probably all know that a
-big sort implies producing "runs" (which are pre-sorted sequences, which size is
+big sort implies producing "runs" (which are pre-sorted sequences, whose size is
 usually related to the amount of CPU memory), followed by a merging passes for
 these runs, which merging is often very cleverly organised [#]_. It is very
 important that the initial sort produces the longest runs possible.  Tournaments
-are a good way to that.  If, using all the memory available to hold a
+are a good way to achieve that.  If, using all the memory available to hold a
 tournament, you replace and percolate items that happen to fit the current run,
 you'll produce runs which are twice the size of the memory for random input, and
 much better for input fuzzily ordered.
index 9e68f45..d9d81df 100644 (file)
@@ -185,14 +185,14 @@ can be handled using simple textual substitution in the Latin-1 character set
 
 .. data:: name2codepoint
 
-   A dictionary that maps HTML entity names to the Unicode codepoints.
+   A dictionary that maps HTML entity names to the Unicode code points.
 
    .. versionadded:: 2.3
 
 
 .. data:: codepoint2name
 
-   A dictionary that maps Unicode codepoints to HTML entity names.
+   A dictionary that maps Unicode code points to HTML entity names.
 
    .. versionadded:: 2.3
 
index 354edb2..45d8295 100644 (file)
@@ -24,6 +24,11 @@ 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`
 uses it to handle URLs that use HTTP and HTTPS.
 
+.. seealso::
+
+    The `Requests package <http://requests.readthedocs.org/>`_
+    is recommended for a higher-level http client interface.
+
 .. note::
 
    HTTPS support is only available if the :mod:`socket` module was compiled with
@@ -433,9 +438,16 @@ HTTPConnection Objects
    and the selector *url*.  If the *body* argument is present, it should be a
    string of data to send after the headers are finished. Alternatively, it may
    be an open 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 correct value. The *headers*
-   argument should be a mapping of extra HTTP headers to send with the request.
+   file object should support ``fileno()`` and ``read()`` methods. The
+   *headers* argument should be a mapping of extra HTTP headers to send with
+   the request.
+
+   If one is not provided in *headers*, a ``Content-Length`` header is added
+   automatically for all methods if the length of the body can be determined,
+   either from the length of the ``str`` representation, or from the reported
+   size of the file on disk. If *body* is ``None`` the header is not set except
+   for methods that expect a body (``PUT``, ``POST``, and ``PATCH``) in which
+   case it is set to ``0``.
 
    .. versionchanged:: 2.6
       *body* can be a file object.
@@ -579,13 +591,13 @@ Examples
 Here is an example session that uses the ``GET`` method::
 
    >>> import httplib
-   >>> conn = httplib.HTTPConnection("www.python.org")
-   >>> conn.request("GET", "/index.html")
+   >>> conn = httplib.HTTPSConnection("www.python.org")
+   >>> conn.request("GET", "/")
    >>> r1 = conn.getresponse()
    >>> print r1.status, r1.reason
    200 OK
    >>> data1 = r1.read()
-   >>> conn.request("GET", "/parrot.spam")
+   >>> conn.request("GET", "/")
    >>> r2 = conn.getresponse()
    >>> print r2.status, r2.reason
    404 Not Found
@@ -596,8 +608,8 @@ Here is an example session that uses the ``HEAD`` method.  Note that the
 ``HEAD`` method never returns any data. ::
 
    >>> import httplib
-   >>> conn = httplib.HTTPConnection("www.python.org")
-   >>> conn.request("HEAD","/index.html")
+   >>> conn = httplib.HTTPSConnection("www.python.org")
+   >>> conn.request("HEAD","/")
    >>> res = conn.getresponse()
    >>> print res.status, res.reason
    200 OK
index 36d78b0..c842b26 100644 (file)
 IDLE
 ====
 
-.. moduleauthor:: Guido van Rossum <guido@Python.org>
-
 .. index::
    single: IDLE
    single: Python Editor
    single: Integrated Development Environment
 
+.. moduleauthor:: Guido van Rossum <guido@Python.org>
+
 IDLE is the Python IDE built with the :mod:`tkinter` GUI toolkit.
 
 IDLE has the following features:
 
 * coded in 100% pure Python, using the :mod:`tkinter` GUI toolkit
 
-* cross-platform: works on Windows and Unix
+* cross-platform: works on Windows, Unix, and Mac OS X
 
-* multi-window text editor with multiple undo, Python colorizing and many other
-  features, e.g. smart indent and call tips
+* multi-window text editor with multiple undo, Python colorizing,
+  smart indent, call tips, and many other features
 
 * Python shell window (a.k.a. interactive interpreter)
 
-* debugger (not complete, but you can set breakpoints, view  and step)
+* debugger (not complete, but you can set breakpoints, view and step)
 
 
 Menus
 -----
 
+IDLE has two main window types, the Shell window and the Editor window.  It is
+possible to have multiple editor windows simultaneously.  Output windows, such
+as used for Edit / Find in Files, are a subtype of edit window.  They currently
+have the same top menu as Editor windows but a different default title and
+context menu.
 
-File menu
-^^^^^^^^^
+IDLE's menus dynamically change based on which window is currently selected.
+Each menu documented below indicates which window type it is associated with.
+Click on the dotted line at the top of a menu to "tear it off": a separate
+window containing the menu is created (for Unix and Windows only).
 
-New file
-   create a new file editing window
+File menu (Shell and Editor)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Open...
-   open an existing file
+New File
+   Create a new file editing window.
 
-Open module...
-   open an existing module (searches sys.path)
+Open...
+   Open an existing file with an Open dialog.
 
-Class browser
-   show classes and methods in current file
+Recent Files
+   Open a list of recent files.  Click one to open it.
 
-Path browser
-   show sys.path directories, modules, classes and methods
+Open Module...
+   Open an existing module (searches sys.path).
 
 .. index::
    single: Class browser
    single: Path browser
 
+Class Browser
+   Show functions, classes, and methods in the current Editor file in a
+   tree structure.  In the shell, open a module first.
+
+Path Browser
+   Show sys.path directories, modules, functions, classes and methods in a
+   tree structure.
+
 Save
-   save current window to the associated file (unsaved windows have a \* before and
-   after the window title)
+   Save the current window to the associated file, if there is one.  Windows
+   that have been changed since being opened or last saved have a \* before
+   and after the window title.  If there is no associated file,
+   do Save As instead.
 
 Save As...
-   save current window to new file, which becomes the associated file
+   Save the current window with a Save As dialog.  The file saved becomes the
+   new associated file for the window.
 
 Save Copy As...
-   save current window to different file without changing the associated file
+   Save the current window to different file without changing the associated
+   file.
+
+Print Window
+   Print the current window to the default printer.
 
 Close
-   close current window (asks to save if unsaved)
+   Close the current window (ask to save if unsaved).
 
 Exit
-   close all windows and quit IDLE (asks to save if unsaved)
+   Close all windows and quit IDLE (ask to save unsaved windows).
 
-
-Edit menu
-^^^^^^^^^
+Edit menu (Shell and Editor)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Undo
-   Undo last change to current window (max 1000 changes)
+   Undo the last change to the current window.  A maximum of 1000 changes may
+   be undone.
 
 Redo
-   Redo last undone change to current window
+   Redo the last undone change to the current window.
 
 Cut
-   Copy selection into system-wide clipboard; then delete selection
+   Copy selection into the system-wide clipboard; then delete the selection.
 
 Copy
-   Copy selection into system-wide clipboard
+   Copy selection into the system-wide clipboard.
 
 Paste
-   Insert system-wide clipboard into window
+   Insert contents of the system-wide clipboard into the current window.
+
+The clipboard functions are also available in context menus.
 
 Select All
-   Select the entire contents of the edit buffer
+   Select the entire contents of the current window.
 
 Find...
-   Open a search dialog box with many options
+   Open a search dialog with many options
 
-Find again
-   Repeat last search
+Find Again
+   Repeat the last search, if there is one.
 
-Find selection
-   Search for the string in the selection
+Find Selection
+   Search for the currently selected string, if there is one.
 
 Find in Files...
-   Open a search dialog box for searching files
+   Open a file search dialog.  Put results in an new output window.
 
 Replace...
-   Open a search-and-replace dialog box
+   Open a search-and-replace dialog.
 
-Go to line
-   Ask for a line number and show that line
+Go to Line
+   Move cursor to the line number requested and make that line visible.
 
-Indent region
-   Shift selected lines right 4 spaces
+Show Completions
+   Open a scrollable list allowing selection of keywords and attributes. See
+   Completions in the Tips sections below.
 
-Dedent region
-   Shift selected lines left 4 spaces
+Expand Word
+   Expand a prefix you have typed to match a full word in the same window;
+   repeat to get a different expansion.
 
-Comment out region
-   Insert ## in front of selected lines
+Show call tip
+   After an unclosed parenthesis for a function, open a small window with
+   function parameter hints.
 
-Uncomment region
-   Remove leading # or ## from selected lines
+Show surrounding parens
+   Highlight the surrounding parenthesis.
 
-Tabify region
-   Turns *leading* stretches of spaces into tabs
+Format menu (Editor window only)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Untabify region
-   Turn *all* tabs into the right number of spaces
+Indent Region
+   Shift selected lines right by the indent width (default 4 spaces).
 
-Expand word
-   Expand the word you have typed to match another word in the same buffer; repeat
-   to get a different expansion
+Dedent Region
+   Shift selected lines left by the indent width (default 4 spaces).
 
-Format Paragraph
-   Reformat the current blank-line-separated paragraph
+Comment Out Region
+   Insert ## in front of selected lines.
+
+Uncomment Region
+   Remove leading # or ## from selected lines.
+
+Tabify Region
+   Turn *leading* stretches of spaces into tabs. (Note: We recommend using
+   4 space blocks to indent Python code.)
 
-Import module
-   Import or reload the current module
+Untabify Region
+   Turn *all* tabs into the correct number of spaces.
 
-Run script
-   Execute the current file in the __main__ namespace
+Toggle Tabs
+   Open a dialog to switch between indenting with spaces and tabs.
+
+New Indent Width
+   Open a dialog to change indent width. The accepted default by the Python
+   community is 4 spaces.
+
+Format Paragraph
+   Reformat the current blank-line-delimited paragraph in comment block or
+   multiline string or selected line in a string.  All lines in the
+   paragraph will be formatted to less than N columns, where N defaults to 72.
+
+Strip trailing whitespace
+   Remove any space characters after the last non-space character of a line.
 
 .. index::
-   single: Import module
    single: Run script
 
+Run menu (Editor window only)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Windows menu
-^^^^^^^^^^^^
+Python Shell
+   Open or wake up the Python Shell window.
 
-Zoom Height
-   toggles the window between normal size (24x80) and maximum height.
+Check Module
+   Check the syntax of the module currently open in the Editor window. If the
+   module has not been saved IDLE will either prompt the user to save or
+   autosave, as selected in the General tab of the Idle Settings dialog.  If
+   there is a syntax error, the approximate location is indicated in the
+   Editor window.
 
-The rest of this menu lists the names of all open windows; select one to bring
-it to the foreground (deiconifying it if necessary).
+Run Module
+   Do Check Module (above).  If no error, restart the shell to clean the
+   environment, then execute the module.
 
+Shell menu (Shell window only)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Debug menu
-^^^^^^^^^^
+View Last Restart
+  Scroll the shell window to the last Shell restart.
 
-* in the Python Shell window only
+Restart Shell
+  Restart the shell to clean the environment.
 
-Go to file/line
-   Look around the insert point for a filename and line number, open the file,
-   and show the line.  Useful to view the source lines referenced in an
-   exception traceback.
+Debug menu (Shell window only)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Go to File/Line
+   Look on the current line. with the cursor, and the line above for a filename
+   and line number.  If found, open the file if not already open, and show the
+   line.  Use this to view source lines referenced in an exception traceback
+   and lines found by Find in Files. Also available in the context menu of
+   the Shell window and Output windows.
+
+.. index::
+   single: debugger
+   single: stack viewer
 
-Debugger
-   Run commands in the shell under the debugger.
+Debugger (toggle)
+   When actived, code entered in the Shell or run from an Editor will run
+   under the debugger.  In the Editor, breakpoints can be set with the context
+   menu.  This feature is still incomplete and somewhat experimental.
 
-Stack viewer
-   Show the stack traceback of the last exception.
+Stack Viewer
+   Show the stack traceback of the last exception in a tree widget, with
+   access to locals and globals.
 
 Auto-open Stack Viewer
-   Open stack viewer on traceback.
+   Toggle automatically opening the stack viewer on an unhandled exception.
 
-.. index::
-   single: stack viewer
-   single: debugger
+Options menu (Shell and Editor)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
+Configure IDLE
+   Open a configuration dialog.  Fonts, indentation, keybindings, and color
+   themes may be altered.  Startup Preferences may be set, and additional
+   help sources can be specified.  Non-default user setting are saved in a
+   .idlerc directory in the user's home directory.  Problems caused by bad user
+   configuration files are solved by editing or deleting one or more of the
+   files in .idlerc.
 
-Edit context menu
-^^^^^^^^^^^^^^^^^
+Configure Extensions
+   Open a configuration dialog for setting preferences for extensions
+   (discussed below).  See note above about the location of user settings.
 
-* Right-click in Edit window (Control-click on OS X)
+Code Context (toggle)(Editor Window only)
+   Open a pane at the top of the edit window which shows the block context
+   of the code which has scrolled above the top of the window.
 
-Cut
-   Copy selection into system-wide clipboard; then delete selection
+Window menu (Shell and Editor)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Copy
-   Copy selection into system-wide clipboard
+Zoom Height
+   Toggles the window between normal size and maximum height. The initial size
+   defaults to 40 lines by 80 chars unless changed on the General tab of the
+   Configure IDLE dialog.
 
-Paste
-   Insert system-wide clipboard into window
+The rest of this menu lists the names of all open windows; select one to bring
+it to the foreground (deiconifying it if necessary).
 
-Set Breakpoint
-   Sets a breakpoint.  Breakpoints are only enabled when the debugger is open.
+Help menu (Shell and Editor)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Clear Breakpoint
-   Clears the breakpoint on that line.
+About IDLE
+   Display version, copyright, license, credits, and more.
+
+IDLE Help
+   Display a help file for IDLE detailing the menu options, basic editing and
+   navigation, and other tips.
+
+Python Docs
+   Access local Python documentation, if installed, or start a web browser
+   and open docs.python.org showing the latest Python documentation.
+
+Turtle Demo
+   Run the turtledemo module with example python code and turtle drawings.
+
+Additional help sources may be added here with the Configure IDLE dialog under
+the General tab.
 
 .. index::
    single: Cut
@@ -206,38 +297,78 @@ Clear Breakpoint
    single: Clear Breakpoint
    single: breakpoints
 
+Context Menus
+^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Shell context menu
-^^^^^^^^^^^^^^^^^^
-
-* Right-click in Python Shell window (Control-click on OS X)
+Open a context menu by right-clicking in a window (Control-click on OS X).
+Context menus have the standard clipboard functions also on the Edit menu.
 
 Cut
-   Copy selection into system-wide clipboard; then delete selection
+   Copy selection into the system-wide clipboard; then delete the selection.
 
 Copy
-   Copy selection into system-wide clipboard
+   Copy selection into the system-wide clipboard.
 
 Paste
-   Insert system-wide clipboard into window
+   Insert contents of the system-wide clipboard into the current window.
+
+Editor windows also have breakpoint functions.  Lines with a breakpoint set are
+specially marked.  Breakpoints only have an effect when running under the
+debugger.  Breakpoints for a file are saved in the user's .idlerc directory.
+
+Set Breakpoint
+   Set a breakpoint on the current line.
+
+Clear Breakpoint
+   Clear the breakpoint on that line.
+
+Shell and Output windows have the following.
 
 Go to file/line
    Same as in Debug menu.
 
 
-Basic editing and navigation
-----------------------------
+Editing and navigation
+----------------------
+
+In this section, 'C' refers to the Control key on Windows and Unix and
+the Command key on Mac OSX.
 
 * :kbd:`Backspace` deletes to the left; :kbd:`Del` deletes to the right
 
+* :kbd:`C-Backspace` delete word left; :kbd:`C-Del` delete word to the right
+
 * Arrow keys and :kbd:`Page Up`/:kbd:`Page Down` to move around
 
+* :kbd:`C-LeftArrow` and :kbd:`C-RightArrow` moves by words
+
 * :kbd:`Home`/:kbd:`End` go to begin/end of line
 
 * :kbd:`C-Home`/:kbd:`C-End` go to begin/end of file
 
-* Some :program:`Emacs` bindings may also work, including :kbd:`C-B`,
-  :kbd:`C-P`, :kbd:`C-A`, :kbd:`C-E`, :kbd:`C-D`, :kbd:`C-L`
+* Some useful Emacs bindings are inherited from Tcl/Tk:
+
+   * :kbd:`C-a` beginning of line
+
+   * :kbd:`C-e` end of line
+
+   * :kbd:`C-k` kill line (but doesn't put it in clipboard)
+
+   * :kbd:`C-l` center window around the insertion point
+
+   * :kbd:`C-b` go backwards one character without deleting (usually you can
+     also use the cursor key for this)
+
+   * :kbd:`C-f` go forward one character without deleting (usually you can
+     also use the cursor key for this)
+
+   * :kbd:`C-p` go up one line (usually you can also use the cursor key for
+     this)
+
+   * :kbd:`C-d` delete next character
+
+Standard keybindings (like :kbd:`C-c` to copy and :kbd:`C-v` to paste)
+may work.  Keybindings are selected in the Configure IDLE dialog.
 
 
 Automatic indentation
@@ -246,27 +377,75 @@ Automatic indentation
 After a block-opening statement, the next line is indented by 4 spaces (in the
 Python Shell window by one tab).  After certain keywords (break, return etc.)
 the next line is dedented.  In leading indentation, :kbd:`Backspace` deletes up
-to 4 spaces if they are there. :kbd:`Tab` inserts 1-4 spaces (in the Python
-Shell window one tab). See also the indent/dedent region commands in the edit
-menu.
-
+to 4 spaces if they are there. :kbd:`Tab` inserts spaces (in the Python
+Shell window one tab), number depends on Indent width. Currently tabs
+are restricted to four spaces due to Tcl/Tk limitations.
+
+See also the indent/dedent region commands in the edit menu.
+
+Completions
+^^^^^^^^^^^
+
+Completions are supplied for functions, classes, and attributes of classes,
+both built-in and user-defined. Completions are also provided for
+filenames.
+
+The AutoCompleteWindow (ACW) will open after a predefined delay (default is
+two seconds) after a '.' or (in a string) an os.sep is typed. If after one
+of those characters (plus zero or more other characters) a tab is typed
+the ACW will open immediately if a possible continuation is found.
+
+If there is only one possible completion for the characters entered, a
+:kbd:`Tab` will supply that completion without opening the ACW.
+
+'Show Completions' will force open a completions window, by default the
+:kbd:`C-space` will open a completions window. In an empty
+string, this will contain the files in the current directory. On a
+blank line, it will contain the built-in and user-defined functions and
+classes in the current name spaces, plus any modules imported. If some
+characters have been entered, the ACW will attempt to be more specific.
+
+If a string of characters is typed, the ACW selection will jump to the
+entry most closely matching those characters.  Entering a :kbd:`tab` will
+cause the longest non-ambiguous match to be entered in the Editor window or
+Shell.  Two :kbd:`tab` in a row will supply the current ACW selection, as
+will return or a double click.  Cursor keys, Page Up/Down, mouse selection,
+and the scroll wheel all operate on the ACW.
+
+"Hidden" attributes can be accessed by typing the beginning of hidden
+name after a '.', e.g. '_'. This allows access to modules with
+``__all__`` set, or to class-private attributes.
+
+Completions and the 'Expand Word' facility can save a lot of typing!
+
+Completions are currently limited to those in the namespaces. Names in
+an Editor window which are not via ``__main__`` and :data:`sys.modules` will
+not be found.  Run the module once with your imports to correct this situation.
+Note that IDLE itself places quite a few modules in sys.modules, so
+much can be found by default, e.g. the re module.
+
+If you don't like the ACW popping up unbidden, simply make the delay
+longer or disable the extension.  Or another option is the delay could
+be set to zero. Another alternative to preventing ACW popups is to
+disable the call tips extension.
 
 Python Shell window
 ^^^^^^^^^^^^^^^^^^^
 
-* :kbd:`C-C` interrupts executing command
+* :kbd:`C-c` interrupts executing command
 
-* :kbd:`C-D` sends end-of-file; closes window if typed at a ``>>>`` prompt
+* :kbd:`C-d` sends end-of-file; closes window if typed at a ``>>>`` prompt
 
-* :kbd:`Alt-p` retrieves previous command matching what you have typed
+* :kbd:`Alt-/` (Expand word) is also useful to reduce typing
 
-* :kbd:`Alt-n` retrieves next
+  Command history
 
-* :kbd:`Return` while on any previous command retrieves that command
+  * :kbd:`Alt-p` retrieves previous command matching what you have typed. On
+    OS X use :kbd:`C-p`.
 
-* :kbd:`Alt-/` (Expand word) is also useful here
+  * :kbd:`Alt-n` retrieves next. On OS X use :kbd:`C-n`.
 
-.. index:: single: indentation
+  * :kbd:`Return` while on any previous command retrieves that command
 
 
 Syntax colors
@@ -308,17 +487,17 @@ Startup
 
 Upon startup with the ``-s`` option, IDLE will execute the file referenced by
 the environment variables :envvar:`IDLESTARTUP` or :envvar:`PYTHONSTARTUP`.
-Idle first checks for ``IDLESTARTUP``; if ``IDLESTARTUP`` is present the file
-referenced is run.  If ``IDLESTARTUP`` is not present, Idle checks for
+IDLE first checks for ``IDLESTARTUP``; if ``IDLESTARTUP`` is present the file
+referenced is run.  If ``IDLESTARTUP`` is not present, IDLE checks for
 ``PYTHONSTARTUP``.  Files referenced by these environment variables are
-convenient places to store functions that are used frequently from the Idle
+convenient places to store functions that are used frequently from the IDLE
 shell, or for executing import statements to import common modules.
 
 In addition, ``Tk`` also loads a startup file if it is present.  Note that the
 Tk file is loaded unconditionally.  This additional file is ``.Idle.py`` and is
 looked for in the user's home directory.  Statements in this file will be
-executed in the Tk namespace, so this file is not useful for importing functions
-to be used from Idle's Python shell.
+executed in the Tk namespace, so this file is not useful for importing
+functions to be used from IDLE's Python shell.
 
 
 Command line usage
@@ -344,8 +523,71 @@ If there are arguments:
 
 #. 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;
-   the arguments are still available in ``sys.argv``.
+   ``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;    the arguments are still available in ``sys.argv``.
+
+Running without a subprocess
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If IDLE is started with the -n command line switch it will run in a
+single process and will not create the subprocess which runs the RPC
+Python execution server.  This can be useful if Python cannot create
+the subprocess or the RPC socket interface on your platform.  However,
+in this mode user code is not isolated from IDLE itself.  Also, the
+environment is not restarted when Run/Run Module (F5) is selected.  If
+your code has been modified, you must reload() the affected modules and
+re-import any specific items (e.g. from foo import baz) if the changes
+are to take effect.  For these reasons, it is preferable to run IDLE
+with the default subprocess if at all possible.
+
+.. deprecated:: 3.4
+
+
+Help and preferences
+--------------------
+
+Additional help sources
+^^^^^^^^^^^^^^^^^^^^^^^
+
+IDLE includes a help menu entry called "Python Docs" that will open the
+extensive sources of help, including tutorials, available at docs.python.org.
+Selected URLs can be added or removed from the help menu at any time using the
+Configure IDLE dialog. See the IDLE help option in the help menu of IDLE for
+more information.
+
+
+Setting preferences
+^^^^^^^^^^^^^^^^^^^
+
+The font preferences, highlighting, keys, and general preferences can be
+changed via Configure IDLE on the Option menu.  Keys can be user defined;
+IDLE ships with four built in key sets. In addition a user can create a
+custom key set in the Configure IDLE dialog under the keys tab.
+
+
+Extensions
+^^^^^^^^^^
+
+IDLE contains an extension facility.  Peferences for extensions can be
+changed with Configure Extensions. See the beginning of config-extensions.def
+in the idlelib directory for further information.  The default extensions
+are currently:
+
+* FormatParagraph
+
+* AutoExpand
+
+* ZoomHeight
+
+* ScriptBinding
+
+* CallTips
+
+* ParenMatch
+
+* AutoComplete
 
+* CodeContext
 
+* RstripExtension
index 4b465d9..97cf3ea 100644 (file)
@@ -20,7 +20,7 @@ everyday programming. Some of these modules are explicitly designed to
 encourage and enhance the portability of Python programs by abstracting
 away platform-specifics into platform-neutral APIs.
 
-The Python installers for the Windows platform usually includes
+The Python installers for the Windows platform usually include
 the entire standard library and often also include many additional
 components. For Unix-like operating systems Python is normally provided
 as a collection of packages, so it may be necessary to use the packaging
index caee953..6db8f97 100644 (file)
@@ -8,9 +8,11 @@
 .. versionadded:: 2.6
 
 `JSON (JavaScript Object Notation) <http://json.org>`_, specified by
-:rfc:`4627`, is a lightweight data interchange format based on a subset of
-`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ syntax (`ECMA-262 3rd
-edition <http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf>`_).
+:rfc:`7159` (which obsoletes :rfc:`4627`) and by
+`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_,
+is a lightweight data interchange format inspired by
+`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
+(although it is not a strict subset of JavaScript [#rfc-errata]_ ).
 
 :mod:`json` exposes an API familiar to users of the standard library
 :mod:`marshal` and :mod:`pickle` modules.
@@ -485,18 +487,18 @@ Encoders and Decoders
                 mysocket.write(chunk)
 
 
-Standard Compliance
--------------------
+Standard Compliance and Interoperability
+----------------------------------------
 
-The JSON format is specified by :rfc:`4627`.  This section details this
-module's level of compliance with the RFC.  For simplicity,
-:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
-than those explicitly mentioned, are not considered.
+The JSON format is specified by :rfc:`7159` and by
+`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_.
+This section details this module's level of compliance with the RFC.
+For simplicity, :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and
+parameters other than those explicitly mentioned, are not considered.
 
 This module does not comply with the RFC in a strict fashion, implementing some
 extensions that are valid JavaScript but not valid JSON.  In particular:
 
-- Top-level non-object, non-array values are accepted and output;
 - Infinite and NaN number values are accepted and output;
 - Repeated names within an object are accepted, and only the value of the last
   name-value pair is used.
@@ -508,48 +510,30 @@ default settings.
 Character Encodings
 ^^^^^^^^^^^^^^^^^^^
 
-The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
-UTF-32, with UTF-8 being the default.  Accordingly, this module uses UTF-8 as
-the default for its *encoding* parameter.
+The RFC requires that JSON be represented using either UTF-8, UTF-16, or
+UTF-32, with UTF-8 being the recommended default for maximum interoperability.
+Accordingly, this module uses UTF-8 as the default for its *encoding* parameter.
 
 This module's deserializer only directly works with ASCII-compatible encodings;
 UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
 workarounds described in the documentation for the deserializer's *encoding*
 parameter.
 
-The RFC also non-normatively describes a limited encoding detection technique
-for JSON texts; this module's deserializer does not implement this or any other
-kind of encoding detection.
-
 As permitted, though not required, by the RFC, this module's serializer sets
 *ensure_ascii=True* by default, thus escaping the output so that the resulting
 strings only contain ASCII characters.
 
+The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
+and this module's serializer does not add a BOM to its output.
+The RFC permits, but does not require, JSON deserializers to ignore an initial
+BOM in their input.  This module's deserializer raises a :exc:`ValueError`
+when an initial BOM is present.
 
-Top-level Non-Object, Non-Array Values
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-The RFC specifies that the top-level value of a JSON text must be either a
-JSON object or array (Python :class:`dict` or :class:`list`).  This module's
-deserializer also accepts input texts consisting solely of a
-JSON null, boolean, number, or string value::
-
-   >>> just_a_json_string = '"spam and eggs"'  # Not by itself a valid JSON text
-   >>> json.loads(just_a_json_string)
-   u'spam and eggs'
-
-This module itself does not include a way to request that such input texts be
-regarded as illegal.  Likewise, this module's serializer also accepts single
-Python :data:`None`, :class:`bool`, numeric, and :class:`str`
-values as input and will generate output texts consisting solely of a top-level
-JSON null, boolean, number, or string value without raising an exception::
-
-   >>> neither_a_list_nor_a_dict = u"spam and eggs"
-   >>> json.dumps(neither_a_list_nor_a_dict)  # The result is not a valid JSON text
-   '"spam and eggs"'
-
-This module's serializer does not itself include a way to enforce the
-aforementioned constraint.
+The RFC does not explicitly forbid JSON strings which contain byte sequences
+that don't correspond to valid Unicode characters (e.g. unpaired UTF-16
+surrogates), but it does note that they may cause interoperability problems.
+By default, this module accepts and outputs (when present in the original
+:class:`str`) code points for such sequences.
 
 
 Infinite and NaN Number Values
@@ -579,7 +563,7 @@ Repeated Names Within an Object
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 The RFC specifies that the names within a JSON object should be unique, but
-does not specify how repeated names in JSON objects should be handled.  By
+does not mandate how repeated names in JSON objects should be handled.  By
 default, this module does not raise an exception; instead, it ignores all but
 the last name-value pair for a given name::
 
@@ -588,3 +572,48 @@ the last name-value pair for a given name::
    {u'x': 3}
 
 The *object_pairs_hook* parameter can be used to alter this behavior.
+
+
+Top-level Non-Object, Non-Array Values
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The old version of JSON specified by the obsolete :rfc:`4627` required that
+the top-level value of a JSON text must be either a JSON object or array
+(Python :class:`dict` or :class:`list`), and could not be a JSON null,
+boolean, number, or string value.  :rfc:`7159` removed that restriction, and
+this module does not and has never implemented that restriction in either its
+serializer or its deserializer.
+
+Regardless, for maximum interoperability, you may wish to voluntarily adhere
+to the restriction yourself.
+
+
+Implementation Limitations
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Some JSON deserializer implementations may set limits on:
+
+* the size of accepted JSON texts
+* the maximum level of nesting of JSON objects and arrays
+* the range and precision of JSON numbers
+* the content and maximum length of JSON strings
+
+This module does not impose any such limits beyond those of the relevant
+Python datatypes themselves or the Python interpreter itself.
+
+When serializing to JSON, beware any such limitations in applications that may
+consume your JSON.  In particular, it is common for JSON numbers to be
+deserialized into IEEE 754 double precision numbers and thus subject to that
+representation's range and precision limitations.  This is especially relevant
+when serializing Python :class:`int` values of extremely large magnitude, or
+when serializing instances of "exotic" numerical types such as
+:class:`decimal.Decimal`.
+
+
+.. rubric:: Footnotes
+
+.. [#rfc-errata] As noted in `the errata for RFC 7159
+   <http://www.rfc-editor.org/errata_search.php?rfc=7159>`_,
+   JSON permits literal U+2028 (LINE SEPARATOR) and
+   U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
+   (as of ECMAScript Edition 5.1) does not.
index fddb644..5460c3a 100644 (file)
@@ -580,6 +580,18 @@ 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]``.
 
+.. note::
+
+   The :func:`fileConfig` API is older than the :func:`dictConfig` API and does
+   not provide functionality to cover certain aspects of logging. For example,
+   you cannot configure :class:`~logging.Filter` objects, which provide for
+   filtering of messages beyond simple integer levels, using :func:`fileConfig`.
+   If you need to have instances of :class:`~logging.Filter` in your logging
+   configuration, you will need to use :func:`dictConfig`. Note that future
+   enhancements to configuration functionality will be added to
+   :func:`dictConfig`, so it's worth considering transitioning to this newer
+   API when it's convenient to do so.
+
 Examples of these sections in the file are given below. ::
 
    [loggers]
index d0f9be8..6731abc 100644 (file)
@@ -185,15 +185,16 @@ module, supports rotation of disk log files.
    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.
+   whenever the current log file is nearly *maxBytes* in length; if either of
+   *maxBytes* or *backupCount* 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.
 
    .. versionchanged:: 2.6
       *delay* was added.
index 839bdc7..9f778f5 100644 (file)
@@ -227,8 +227,9 @@ is the module's name in the Python package namespace.
 .. method:: Logger.exception(msg, *args, **kwargs)
 
    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.
+   interpreted as for :meth:`debug`, except that any passed *exc_info* is not
+   inspected. Exception info is always added to the logging message. This method
+   should only be called from an exception handler.
 
 
 .. method:: Logger.addFilter(filt)
@@ -439,7 +440,9 @@ Formatter Objects
 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.
+supplied, the default value of ``'%(message)s'`` is used, which just includes
+the message in the logging call. To have additional items of information in the
+formatted output (such as a timestamp), keep reading.
 
 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
@@ -845,8 +848,9 @@ functions.
 .. function:: exception(msg[, *args[, **kwargs]])
 
    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.
+   interpreted as for :func:`debug`, except that any passed *exc_info* is not
+   inspected. Exception info is always added to the logging message. This
+   function should only be called from an exception handler.
 
 
 .. function:: log(level, msg[, *args[, **kwargs]])
index 740c2f6..0b7fc92 100644 (file)
@@ -106,8 +106,8 @@ behavior of the module.
    extension is already known, the new type will replace the old one. When the type
    is already known the extension will be added to the list of known extensions.
 
-   When *strict* is ``True`` (the default), the mapping will added to the official MIME
-   types, otherwise to the non-standard ones.
+   When *strict* is ``True`` (the default), the mapping will be added to the
+   official MIME types, otherwise to the non-standard ones.
 
 
 .. data:: inited
index fb8ddfb..021e3c8 100644 (file)
@@ -18,41 +18,27 @@ to this, the :mod:`multiprocessing` module allows the programmer to fully
 leverage multiple processors on a given machine.  It runs on both Unix and
 Windows.
 
-.. warning::
+The :mod:`multiprocessing` module also introduces APIs which do not have
+analogs in the :mod:`threading` module.  A prime example of this is the
+:class:`Pool` object which offers a convenient means of parallelizing the
+execution of a function across multiple input values, distributing the
+input data across processes (data parallelism).  The following example
+demonstrates the common practice of defining such functions in a module so
+that child processes can successfully import that module.  This basic example
+of data parallelism using :class:`Pool`, ::
 
-    Some of this package's functionality requires a functioning shared semaphore
-    implementation on the host operating system. Without one, the
-    :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
-    import it will result in an :exc:`ImportError`. See
-    :issue:`3770` for additional information.
+   from multiprocessing import Pool
 
-.. note::
+   def f(x):
+       return x*x
 
-    Functionality within this package requires that the ``__main__`` module be
-    importable by the children. This is covered in :ref:`multiprocessing-programming`
-    however it is worth pointing out here. This means that some examples, such
-    as the :class:`multiprocessing.Pool` examples will not work in the
-    interactive interpreter. For example::
-
-        >>> from multiprocessing import Pool
-        >>> p = Pool(5)
-        >>> def f(x):
-        ...     return x*x
-        ...
-        >>> p.map(f, [1,2,3])
-        Process PoolWorker-1:
-        Process PoolWorker-2:
-        Process PoolWorker-3:
-        Traceback (most recent call last):
-        Traceback (most recent call last):
-        Traceback (most recent call last):
-        AttributeError: 'module' object has no attribute 'f'
-        AttributeError: 'module' object has no attribute 'f'
-        AttributeError: 'module' object has no attribute 'f'
-
-    (If you try this it will actually output three full tracebacks
-    interleaved in a semi-random fashion, and then you may have to
-    stop the master process somehow.)
+   if __name__ == '__main__':
+       p = Pool(5)
+       print(p.map(f, [1, 2, 3]))
+
+will print to standard output ::
+
+   [1, 4, 9]
 
 
 The :class:`Process` class
@@ -99,7 +85,6 @@ For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
 necessary, see :ref:`multiprocessing-programming`.
 
 
-
 Exchanging objects between processes
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
@@ -290,6 +275,34 @@ For example::
 Note that the methods of a pool should only ever be used by the
 process which created it.
 
+.. note::
+
+   Functionality within this package requires that the ``__main__`` module be
+   importable by the children. This is covered in :ref:`multiprocessing-programming`
+   however it is worth pointing out here. This means that some examples, such
+   as the :class:`Pool` examples will not work in the interactive interpreter.
+   For example::
+
+      >>> from multiprocessing import Pool
+      >>> p = Pool(5)
+      >>> def f(x):
+      ...     return x*x
+      ...
+      >>> p.map(f, [1,2,3])
+      Process PoolWorker-1:
+      Process PoolWorker-2:
+      Process PoolWorker-3:
+      Traceback (most recent call last):
+      Traceback (most recent call last):
+      Traceback (most recent call last):
+      AttributeError: 'module' object has no attribute 'f'
+      AttributeError: 'module' object has no attribute 'f'
+      AttributeError: 'module' object has no attribute 'f'
+
+   (If you try this it will actually output three full tracebacks
+   interleaved in a semi-random fashion, and then you may have to
+   stop the master process somehow.)
+
 
 Reference
 ---------
@@ -638,6 +651,15 @@ For an example of the usage of queues for interprocess communication see
       immediately without waiting to flush enqueued data to the
       underlying pipe, and you don't care about lost data.
 
+   .. note::
+
+      This class's functionality requires a functioning shared semaphore
+      implementation on the host operating system. Without one, the
+      functionality in this class will be disabled, and attempts to
+      instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
+      :issue:`3770` for additional information.  The same holds true for any
+      of the specialized queue types listed below.
+
 
 .. class:: multiprocessing.queues.SimpleQueue()
 
@@ -944,6 +966,14 @@ object -- see :ref:`multiprocessing-managers`.
    This differs from the behaviour of :mod:`threading` where SIGINT will be
    ignored while the equivalent blocking calls are in progress.
 
+.. note::
+
+   Some of this package's functionality requires a functioning shared semaphore
+   implementation on the host operating system. Without one, the
+   :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
+   import it will result in an :exc:`ImportError`. See
+   :issue:`3770` for additional information.
+
 
 Shared :mod:`ctypes` Objects
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
index d75ca18..9ce9a16 100644 (file)
@@ -39,7 +39,7 @@ available for Python:
       low-level device context drawing, drag and drop, system clipboard access,
       an XML-based resource format and more, including an ever growing library
       of user-contributed modules.  wxPython has a book, `wxPython in Action
-      <http://www.amazon.com/exec/obidos/ASIN/1932394621>`_, by Noel Rappin and
+      <http://www.manning.com/rappin/>`_, by Noel Rappin and
       Robin Dunn.
 
 PyGTK, PyQt, and wxPython, all have a modern look and feel and more
index 0fb1489..c7007a6 100644 (file)
@@ -663,7 +663,7 @@ you are using :class:`profile.Profile` or :class:`cProfile.Profile`,
 
       pr = cProfile.Profile(your_integer_time_func, 0.001)
 
-   As the :mod:`cProfile.Profile` class cannot be calibrated, custom timer
+   As the :class:`cProfile.Profile` class cannot be calibrated, custom timer
    functions should be used with care and should be as fast as possible.  For
    the best results with a custom timer, it might be necessary to hard-code it
    in the C source of the internal :mod:`_lsprof` module.
index 494a48d..57521f7 100644 (file)
@@ -53,6 +53,10 @@ produced for that file.
    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.
 
+When printing output to the console, :program:`pydoc` attempts to paginate the
+output for easier reading.  If the :envvar:`PAGER` environment variable is set,
+:program:`pydoc` will use its value as a pagination program.
+
 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.
index db7e1cf..b353c4c 100644 (file)
@@ -276,7 +276,9 @@ The special characters are:
    assertion`. ``(?<=abc)def`` will find a match in ``abcdef``, since the
    lookbehind will back up 3 characters and check if the contained pattern matches.
    The contained pattern must only match strings of some fixed length, meaning that
-   ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not.  Note that
+   ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not.  Group
+   references are not supported even if they match strings of some fixed length.
+   Note that
    patterns which start with positive lookbehind assertions will not match at the
    beginning of the string being searched; you will most likely want to use the
    :func:`search` function rather than the :func:`match` function:
@@ -296,7 +298,8 @@ The special characters are:
    Matches if the current position in the string is not preceded by a match for
    ``...``.  This is called a :dfn:`negative lookbehind assertion`.  Similar to
    positive lookbehind assertions, the contained pattern must only match strings of
-   some fixed length.  Patterns which start with negative lookbehind assertions may
+   some fixed length and shouldn't contain group references.
+   Patterns which start with negative lookbehind assertions may
    match at the beginning of the string being searched.
 
 ``(?(id/name)yes-pattern|no-pattern)``
index fc9e7c1..a08bc94 100644 (file)
@@ -72,6 +72,9 @@ The :mod:`runpy` module provides two functions:
    arguments. It is recommended that the :mod:`sys` module be left alone when
    invoking this function from threaded code.
 
+   .. seealso::
+      The :option:`-m` option offering equivalent functionality from the
+      command line.
 
    .. versionchanged:: 2.7
          Added ability to execute packages by looking for a ``__main__``
@@ -134,14 +137,18 @@ The :mod:`runpy` module provides two functions:
    limitations still apply, use of this function in threaded code should be
    either serialised with the import lock or delegated to a separate process.
 
+   .. seealso::
+      :ref:`using-on-interface-options` for equivalent functionality on the
+      command line (``python path/to/script``).
+
    .. versionadded:: 2.7
 
 .. seealso::
 
-   :pep:`338` - Executing modules as scripts
+   :pep:`338` -- Executing modules as scripts
       PEP written and implemented by Nick Coghlan.
 
-   :pep:`366` - Main module explicit relative imports
+   :pep:`366` -- Main module explicit relative imports
       PEP written and implemented by Nick Coghlan.
 
    :ref:`using-on-general` - CPython command line details
index 1da19cf..84911fe 100644 (file)
@@ -153,7 +153,7 @@ A single exception is defined as well:
 
 .. method:: SGMLParser.convert_codepoint(codepoint)
 
-   Convert a codepoint to a :class:`str` value.  Encodings can be handled here if
+   Convert a code point to a :class:`str` value.  Encodings can be handled here if
    appropriate, though the rest of :mod:`sgmllib` is oblivious on this matter.
 
    .. versionadded:: 2.5
index e897483..f350f5e 100644 (file)
@@ -164,12 +164,9 @@ Directory and files operations
 
    Recursively move a file or directory (*src*) to another location (*dst*).
 
-   If the destination is a directory or a symlink to a directory, then *src* is
-   moved inside that directory.
-
-   The destination directory must not already exist.  If the destination already
-   exists but is not a directory, it may be overwritten depending on
-   :func:`os.rename` semantics.
+   If the destination is an existing directory, then *src* is moved inside that
+   directory. If the destination already exists but is not a directory, it may
+   be overwritten depending on :func:`os.rename` semantics.
 
    If the destination is on the current filesystem, then :func:`os.rename` is
    used.  Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
index 8ef6cbe..c18d2a0 100644 (file)
@@ -192,7 +192,7 @@ instead.
        ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
         *SSLv2*                    yes        no         yes         no         no         no
         *SSLv3*                    no         yes        yes         no         no         no
-        *SSLv23*                   yes        no         yes         no         no         no
+        *SSLv23*                   no         yes        yes         yes        yes        yes
         *TLSv1*                    no         no         yes         yes        no         no
         *TLSv1.1*                  no         no         yes         no         yes        no
         *TLSv1.2*                  no         no         yes         no         no         yes
@@ -201,9 +201,8 @@ instead.
    .. note::
 
       Which connections succeed will vary depending on the version of
-      OpenSSL.  For example, beginning with OpenSSL 1.0.0, an SSLv23 client
-      will not actually attempt SSLv2 connections unless you explicitly
-      enable SSLv2 ciphers (which is not recommended, as SSLv2 is broken).
+      OpenSSL.  For example, before OpenSSL 1.0.0, an SSLv23 client
+      would always attempt SSLv2 connections.
 
    The *ciphers* parameter sets the available ciphers for this SSL object.
    It should be a string in the `OpenSSL cipher list format
@@ -246,14 +245,13 @@ purposes.
    :const:`None`, this function can choose to trust the system's default
    CA certificates instead.
 
-   The settings in Python 2.7.9 are: :data:`PROTOCOL_SSLv23`,
-   :data:`OP_NO_SSLv2`, and :data:`OP_NO_SSLv3` with high encryption cipher
-   suites without RC4 and without unauthenticated cipher suites. Passing
-   :data:`~Purpose.SERVER_AUTH` as *purpose* sets
-   :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED` and either loads CA
-   certificates (when at least one of *cafile*, *capath* or *cadata* is given)
-   or uses :meth:`SSLContext.load_default_certs` to load default CA
-   certificates.
+   The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
+   :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
+   without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
+   as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
+   and either loads CA certificates (when at least one of *cafile*, *capath* or
+   *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load
+   default CA certificates.
 
    .. note::
       The protocol, options, cipher and other settings may change to more
@@ -265,29 +263,33 @@ purposes.
 
    .. note::
       If you find that when certain older clients or servers attempt to connect
-      with a :class:`SSLContext` created by this function that they get an
-      error stating "Protocol or cipher suite mismatch", it may be that they
-      only support SSL3.0 which this function excludes using the
-      :data:`OP_NO_SSLv3`. SSL3.0 has problematic security due to a number of
-      poor implementations and it's reliance on MD5 within the protocol. If you
-      wish to continue to use this function but still allow SSL 3.0 connections
-      you can re-enable them using::
+      with a :class:`SSLContext` created by this function that they get an error
+      stating "Protocol or cipher suite mismatch", it may be that they only
+      support SSL3.0 which this function excludes using the
+      :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken
+      <https://en.wikipedia.org/wiki/POODLE>`_. If you still wish to continue to
+      use this function but still allow SSL 3.0 connections you can re-enable
+      them using::
 
          ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
          ctx.options &= ~ssl.OP_NO_SSLv3
 
    .. versionadded:: 2.7.9
 
+   .. versionchanged:: 2.7.10
+
+     RC4 was dropped from the default cipher string.
+
 
 Random generation
 ^^^^^^^^^^^^^^^^^
 
 .. function:: RAND_status()
 
-   Returns ``True`` if the SSL pseudo-random number generator has been seeded with
-   'enough' randomness, and ``False`` otherwise.  You can use :func:`ssl.RAND_egd`
-   and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
-   number generator.
+   Return ``True`` if the SSL pseudo-random number generator has been seeded
+   with 'enough' randomness, and ``False`` otherwise.  You can use
+   :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of
+   the pseudo-random number generator.
 
 .. function:: RAND_egd(path)
 
@@ -300,9 +302,11 @@ Random generation
    See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
    of entropy-gathering daemons.
 
+   Availability: not available with LibreSSL.
+
 .. function:: RAND_add(bytes, entropy)
 
-   Mixes the given *bytes* into the SSL pseudo-random number generator.  The
+   Mix the given *bytes* into the SSL pseudo-random number generator.  The
    parameter *entropy* (a float) is a lower bound on the entropy contained in
    string (so you can always use :const:`0.0`).  See :rfc:`1750` for more
    information on sources of entropy.
@@ -481,9 +485,9 @@ Constants
 
 .. data:: VERIFY_DEFAULT
 
-   Possible value for :attr:`SSLContext.verify_flags`. In this mode,
-   certificate revocation lists (CRLs) are not checked. By default OpenSSL
-   does neither require nor verify CRLs.
+   Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate
+   revocation lists (CRLs) are not checked. By default OpenSSL does neither
+   require nor verify CRLs.
 
    .. versionadded:: 2.7.9
 
@@ -511,6 +515,14 @@ Constants
 
    .. versionadded:: 2.7.9
 
+.. data:: VERIFY_X509_TRUSTED_FIRST
+
+   Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to
+   prefer trusted certificates when building the trust chain to validate a
+   certificate. This flag is enabled by default.
+
+   .. versionadded:: 2.7.10
+
 .. data:: PROTOCOL_SSLv23
 
    Selects the highest protocol version that both the client and server support.
@@ -637,6 +649,13 @@ Constants
 
    .. versionadded:: 2.7.9
 
+.. data:: HAS_ALPN
+
+   Whether the OpenSSL library has built-in support for the *Application-Layer
+   Protocol Negotiation* TLS extension as described in :rfc:`7301`.
+
+   .. versionadded:: 2.7.10
+
 .. data:: HAS_ECDH
 
    Whether the OpenSSL library has built-in support for Elliptic Curve-based
@@ -863,9 +882,19 @@ SSL sockets also have the following additional methods and attributes:
 
    .. versionadded:: 2.7.9
 
+.. method:: SSLSocket.selected_alpn_protocol()
+
+   Return the protocol that was selected during the TLS handshake.  If
+   :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does
+   not support ALPN, if this socket does not support any of the client's
+   proposed protocols, or if the handshake has not happened yet, ``None`` is
+   returned.
+
+   .. versionadded:: 2.7.10
+
 .. method:: SSLSocket.selected_npn_protocol()
 
-   Returns the higher-level protocol that was selected during the TLS/SSL
+   Return the higher-level protocol that was selected during the TLS/SSL
    handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or
    if the other party does not support NPN, or if the handshake has not yet
    happened, this will return ``None``.
@@ -1033,6 +1062,20 @@ to speed up repeated connections from the same clients.
       when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
       give the currently selected cipher.
 
+.. method:: SSLContext.set_alpn_protocols(protocols)
+
+   Specify which protocols the socket should advertise during the SSL/TLS
+   handshake. It should be a list of ASCII strings, like ``['http/1.1',
+   'spdy/2']``, ordered by preference. The selection of a protocol will happen
+   during the handshake, and will play out according to :rfc:`7301`. After a
+   successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will
+   return the agreed-upon protocol.
+
+   This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
+   False.
+
+   .. versionadded:: 2.7.10
+
 .. method:: SSLContext.set_npn_protocols(protocols)
 
    Specify which protocols the socket should advertise during the SSL/TLS
@@ -1071,7 +1114,7 @@ to speed up repeated connections from the same clients.
 
    Due to the early negotiation phase of the TLS connection, only limited
    methods and attributes are usable like
-   :meth:`SSLSocket.selected_npn_protocol` and :attr:`SSLSocket.context`.
+   :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`.
    :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
    :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
    the TLS connection has progressed beyond the TLS Client Hello and therefore
index fa4304c..bc437a4 100644 (file)
@@ -2031,16 +2031,32 @@ pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
       Return the item of *d* with key *key*.  Raises a :exc:`KeyError` if *key*
       is not in the map.
 
+      .. index:: __missing__()
+
+      If a subclass of dict defines a method :meth:`__missing__` and *key*
+      is not present, the ``d[key]`` operation calls that method with the key *key*
+      as argument.  The ``d[key]`` operation then returns or raises whatever is
+      returned or raised by the ``__missing__(key)`` call.
+      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::
+
+          >>> class Counter(dict):
+          ...     def __missing__(self, key):
+          ...         return 0
+          >>> c = Counter()
+          >>> c['red']
+          0
+          >>> c['red'] += 1
+          >>> c['red']
+          1
+
+      The example above shows part of the implementation of
+      :class:`collections.Counter`.  A different ``__missing__`` method is used
+      by :class:`collections.defaultdict`.
+
       .. versionadded:: 2.5
-         If a subclass of dict defines a method :meth:`__missing__`, if the key
-         *key* is not present, the ``d[key]`` operation calls that method with
-         the key *key* as argument.  The ``d[key]`` operation then returns or
-         raises whatever is 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`.
+         Recognition of __missing__ methods of dict subclasses.
 
    .. describe:: d[key] = value
 
index 04ddef9..be2dd15 100644 (file)
@@ -222,12 +222,13 @@ The module defines the following functions and data items:
 
 .. function:: sleep(secs)
 
-   Suspend execution for the given number of seconds.  The argument may be a
-   floating point number to indicate a more precise sleep time. The actual
-   suspension time may be less than that requested because any caught signal will
-   terminate the :func:`sleep` following execution of that signal's catching
-   routine.  Also, the suspension time may be longer than requested by an arbitrary
-   amount because of the scheduling of other activity in the system.
+   Suspend execution of the current thread for the given number of seconds.
+   The argument may be a floating point number to indicate a more precise sleep
+   time. The actual suspension time may be less than that requested because any
+   caught signal will terminate the :func:`sleep` following execution of that
+   signal's catching routine.  Also, the suspension time may be longer than
+   requested by an arbitrary amount because of the scheduling of other activity
+   in the system.
 
 
 .. function:: strftime(format[, t])
index 29f6959..846f96e 100644 (file)
@@ -35,13 +35,13 @@ is maintained at ActiveState.)
    `Tcl/Tk manual <http://www.tcl.tk/man/tcl8.5/>`_
       Official manual for the latest tcl/tk version.
 
-   `Programming Python <http://www.amazon.com/Programming-Python-Mark-Lutz/dp/0596158106/>`_
+   `Programming Python <http://www.rmi.net/~lutz/about-pp4e.html>`_
       Book by Mark Lutz, has excellent coverage of Tkinter.
 
    `Modern Tkinter for Busy Python Developers <http://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
       Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
 
-   `Python and Tkinter Programming <http://www.amazon.com/exec/obidos/ASIN/1884777813>`_
+   `Python and Tkinter Programming <http://www.manning.com/grayson/>`_
       The book by John Grayson (ISBN 1-884777-81-3).
 
 
@@ -190,7 +190,7 @@ documentation that exists. Here are some hints:
    `Tcl and the Tk Toolkit <http://www.amazon.com/exec/obidos/ASIN/020163337X>`_
       The book by John Ousterhout, the inventor of Tcl.
 
-   `Practical Programming in Tcl and Tk <http://www.amazon.com/exec/obidos/ASIN/0130220280>`_
+   `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
       Brent Welch's encyclopedic book.
 
 
index 556829a..bc3046a 100644 (file)
@@ -87,7 +87,7 @@ need to derive from a specific class.
       Kent Beck's original paper on testing frameworks using the pattern shared
       by :mod:`unittest`.
 
-   `Nose <http://code.google.com/p/python-nose/>`_ and `py.test <http://pytest.org>`_
+   `Nose <https://nose.readthedocs.org/en/latest/>`_ and `py.test <http://pytest.org>`_
       Third-party unittest frameworks with a lighter-weight syntax for writing
       tests.  For example, ``assert func(10) == 42``.
 
@@ -109,37 +109,29 @@ The :mod:`unittest` module provides a rich set of tools for constructing and
 running tests.  This section demonstrates that a small subset of the tools
 suffice to meet the needs of most users.
 
-Here is a short script to test three functions from the :mod:`random` module::
+Here is a short script to test three string methods::
 
-   import random
-   import unittest
-
-   class TestSequenceFunctions(unittest.TestCase):
+  import unittest
 
-       def setUp(self):
-           self.seq = range(10)
+  class TestStringMethods(unittest.TestCase):
 
-       def test_shuffle(self):
-           # make sure the shuffled sequence does not lose any elements
-           random.shuffle(self.seq)
-           self.seq.sort()
-           self.assertEqual(self.seq, range(10))
+    def test_upper(self):
+        self.assertEqual('foo'.upper(), 'FOO')
 
-           # should raise an exception for an immutable sequence
-           self.assertRaises(TypeError, random.shuffle, (1,2,3))
+    def test_isupper(self):
+        self.assertTrue('FOO'.isupper())
+        self.assertFalse('Foo'.isupper())
 
-       def test_choice(self):
-           element = random.choice(self.seq)
-           self.assertTrue(element in self.seq)
+    def test_split(self):
+        s = 'hello world'
+        self.assertEqual(s.split(), ['hello', 'world'])
+        # check that s.split fails when the separator is not a string
+        with self.assertRaises(TypeError):
+            s.split(2)
 
-       def test_sample(self):
-           with self.assertRaises(ValueError):
-               random.sample(self.seq, 20)
-           for element in random.sample(self.seq, 5):
-               self.assertTrue(element in self.seq)
+  if __name__ == '__main__':
+      unittest.main()
 
-   if __name__ == '__main__':
-       unittest.main()
 
 A testcase is created by subclassing :class:`unittest.TestCase`.  The three
 individual tests are defined with methods whose names start with the letters
@@ -147,16 +139,15 @@ individual tests are defined with methods whose names start with the letters
 represent tests.
 
 The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
-expected result; :meth:`~TestCase.assertTrue` to verify a condition; or
-:meth:`~TestCase.assertRaises` to verify that an expected exception gets raised.
-These methods are used instead of the :keyword:`assert` statement so the test
-runner can accumulate all test results and produce a report.
+expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
+to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
+specific exception gets raised.  These methods are used instead of the
+:keyword:`assert` statement so the test runner can accumulate all test results
+and produce a report.
 
-When a :meth:`~TestCase.setUp` method is defined, the test runner will run that
-method prior to each test.  Likewise, if a :meth:`~TestCase.tearDown` method is
-defined, the test runner will invoke that method after each test.  In the
-example, :meth:`~TestCase.setUp` was used to create a fresh sequence for each
-test.
+The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
+to define instructions that will be executed before and after each test method.
+They are covered in more details in the section :ref:`organizing-tests`.
 
 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
@@ -172,18 +163,18 @@ Instead of :func:`unittest.main`, there are other ways to run the tests with a
 finer level of control, less terse output, and no requirement to be run from the
 command line.  For example, the last two lines may be replaced with::
 
-   suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
+   suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
    unittest.TextTestRunner(verbosity=2).run(suite)
 
 Running the revised script from the interpreter or another script produces the
 following output::
 
-   test_choice (__main__.TestSequenceFunctions) ... ok
-   test_sample (__main__.TestSequenceFunctions) ... ok
-   test_shuffle (__main__.TestSequenceFunctions) ... ok
+   test_isupper (__main__.TestStringMethods) ... ok
+   test_split (__main__.TestStringMethods) ... ok
+   test_upper (__main__.TestStringMethods) ... ok
 
    ----------------------------------------------------------------------
-   Ran 3 tests in 0.110s
+   Ran 3 tests in 0.001s
 
    OK
 
index b2a817d..d0cc548 100644 (file)
@@ -24,6 +24,11 @@ built-in function :func:`open`, but accepts Universal Resource Locators (URLs)
 instead of filenames.  Some restrictions apply --- it can only open URLs for
 reading, and no seek operations are available.
 
+.. seealso::
+
+    The `Requests package <http://requests.readthedocs.org/>`_
+    is recommended for a higher-level http client interface.
+
 .. warning:: When opening HTTPS URLs, it does not attempt to validate the
    server certificate.  Use at your own risk!
 
index f599894..3fe4f25 100644 (file)
@@ -18,6 +18,11 @@ The :mod:`urllib2` module defines functions and classes which help in opening
 URLs (mostly HTTP) in a complex world --- basic and digest authentication,
 redirections, cookies and more.
 
+.. seealso::
+
+    The `Requests package <http://requests.readthedocs.org/>`_
+    is recommended for a higher-level http client interface.
+
 
 The :mod:`urllib2` module defines the following functions:
 
index 3afabb4..46396dd 100644 (file)
@@ -266,6 +266,73 @@ sub-elements for a given element::
    >>> ET.dump(a)
    <a><b /><c><d /></c></a>
 
+Parsing XML with Namespaces
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If the XML input has `namespaces
+<https://en.wikipedia.org/wiki/XML_namespace>`__, tags and attributes
+with prefixes in the form ``prefix:sometag`` get expanded to
+``{uri}sometag`` where the *prefix* is replaced by the full *URI*.
+Also, if there is a `default namespace
+<http://www.w3.org/TR/2006/REC-xml-names-20060816/#defaulting>`__,
+that full URI gets prepended to all of the non-prefixed tags.
+
+Here is an XML example that incorporates two namespaces, one with the
+prefix "fictional" and the other serving as the default namespace:
+
+.. code-block:: xml
+
+    <?xml version="1.0"?>
+    <actors xmlns:fictional="http://characters.example.com"
+            xmlns="http://people.example.com">
+        <actor>
+            <name>John Cleese</name>
+            <fictional:character>Lancelot</fictional:character>
+            <fictional:character>Archie Leach</fictional:character>
+        </actor>
+        <actor>
+            <name>Eric Idle</name>
+            <fictional:character>Sir Robin</fictional:character>
+            <fictional:character>Gunther</fictional:character>
+            <fictional:character>Commander Clement</fictional:character>
+        </actor>
+    </actors>
+
+One way to search and explore this XML example is to manually add the
+URI to every tag or attribute in the xpath of a
+:meth:`~Element.find` or :meth:`~Element.findall`::
+
+    root = fromstring(xml_text)
+    for actor in root.findall('{http://people.example.com}actor'):
+        name = actor.find('{http://people.example.com}name')
+        print name.text
+        for char in actor.findall('{http://characters.example.com}character'):
+            print ' |-->', char.text
+
+
+A better way to search the namespaced XML example is to create a
+dictionary with your own prefixes and use those in the search functions::
+
+    ns = {'real_person': 'http://people.example.com',
+          'role': 'http://characters.example.com'}
+
+    for actor in root.findall('real_person:actor', ns):
+        name = actor.find('real_person:name', ns)
+        print name.text
+        for char in actor.findall('role:character', ns):
+            print ' |-->', char.text
+
+These two approaches both output::
+
+    John Cleese
+     |--> Lancelot
+     |--> Archie Leach
+    Eric Idle
+     |--> Sir Robin
+     |--> Gunther
+     |--> Commander Clement
+
+
 Additional resources
 ^^^^^^^^^^^^^^^^^^^^
 
@@ -345,6 +412,10 @@ Supported XPath syntax
 | ``[tag]``             | Selects all elements that have a child named         |
 |                       | ``tag``.  Only immediate children are supported.     |
 +-----------------------+------------------------------------------------------+
+| ``[tag='text']``      | Selects all elements that have a child named         |
+|                       | ``tag`` whose complete text content, including       |
+|                       | descendants, equals the given ``text``.              |
++-----------------------+------------------------------------------------------+
 | ``[position]``        | Selects all elements that are located at the given   |
 |                       | position.  The position can be either an integer     |
 |                       | (1 is the first position), the expression ``last()`` |
index 261747a..173dfb0 100644 (file)
@@ -212,6 +212,8 @@ ZipFile Objects
    to extract to.  *member* can be a filename or a :class:`ZipInfo` object.
    *pwd* is the password used for encrypted files.
 
+   Returns the normalized path created (a directory or new file).
+
    .. versionadded:: 2.6
 
    .. note::
index 6a23fc0..c47f478 100644 (file)
@@ -84,7 +84,7 @@ Terms and conditions for accessing or otherwise using Python
    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-2014 Python Software Foundation; All Rights
+   copyright, i.e., "Copyright © 2001-2015 Python Software Foundation; All Rights
    Reserved" are retained in Python |release| alone or in any derivative version
    prepared by Licensee.
 
index 1070166..251f822 100644 (file)
-@echo off
-setlocal
-
-pushd %~dp0
-
-set this=%~n0
-
-if "%SPHINXBUILD%" EQU "" set SPHINXBUILD=sphinx-build
-if "%PYTHON%" EQU "" set PYTHON=py
-
-if DEFINED ProgramFiles(x86) set _PRGMFLS=%ProgramFiles(x86)%
-if NOT DEFINED ProgramFiles(x86) set _PRGMFLS=%ProgramFiles%
-if "%HTMLHELP%" EQU "" set HTMLHELP=%_PRGMFLS%\HTML Help Workshop\hhc.exe
-
-if "%DISTVERSION%" EQU "" for /f "usebackq" %%v in (`%PYTHON% tools/extensions/patchlevel.py`) do set DISTVERSION=%%v
-
-if "%BUILDDIR%" EQU "" set BUILDDIR=build
-
-rem Targets that don't require sphinx-build
-if "%1" EQU "" goto help
-if "%1" EQU "help" goto help
-if "%1" EQU "check" goto check
-if "%1" EQU "serve" goto serve
-if "%1" == "clean" (
-    rmdir /q /s %BUILDDIR%
-    goto end
-)
-
-%SPHINXBUILD% 2> nul
-if errorlevel 9009 (
-    echo.
-    echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
-    echo.installed, then set the SPHINXBUILD environment variable to point
-    echo.to the full path of the 'sphinx-build' executable. Alternatively you
-    echo.may add the Sphinx directory to PATH.
-    echo.
-    echo.If you don't have Sphinx installed, grab it from
-    echo.http://sphinx-doc.org/
-    goto end
-)
-
-rem Targets that do require sphinx-build and have their own label
-if "%1" EQU "htmlview" goto htmlview
-
-rem Everything else
-goto build
-
-:help
-echo.usage: %this% BUILDER [filename ...]
-echo.
-echo.Call %this% with the desired Sphinx builder as the first argument, e.g.
-echo.``%this% html`` or ``%this% doctest``.  Interesting targets that are
-echo.always available include:
-echo.
-echo.   Provided by Sphinx:
-echo.      html, htmlhelp, latex, text
-echo.      suspicious, linkcheck, changes, doctest
-echo.   Provided by this script:
-echo.      clean, check, serve, htmlview
-echo.
-echo.All arguments past the first one are passed through to sphinx-build as
-echo.filenames to build or are ignored.  See README.txt in this directory or
-echo.the documentation for your version of Sphinx for more exhaustive lists
-echo.of available targets and descriptions of each.
-echo.
-echo.This script assumes that the SPHINXBUILD environment variable contains
-echo.a legitimate command for calling sphinx-build, or that sphinx-build is
-echo.on your PATH if SPHINXBUILD is not set.  Options for sphinx-build can
-echo.be passed by setting the SPHINXOPTS environment variable.
-goto end
-
-:build
-if NOT "%PAPER%" == "" (
-    set SPHINXOPTS=-D latex_paper_size=%PAPER% %SPHINXOPTS%
-)
-cmd /C %SPHINXBUILD% %SPHINXOPTS% -b%1 -dbuild\doctrees . %BUILDDIR%\%*
-
-if "%1" EQU "htmlhelp" (
-    if  not exist "%HTMLHELP%" (
-        echo.
-        echo.The HTML Help Workshop was not found.  Set the HTMLHELP variable
-        echo.to the path to hhc.exe or download and install it from
-        echo.http://msdn.microsoft.com/en-us/library/ms669985
-        rem Set errorlevel to 1 and exit
-        cmd /C exit /b 1
-        goto end
-    )
-    cmd /C "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp
-    rem hhc.exe seems to always exit with code 1, reset to 0 for less than 2
-    if not errorlevel 2 cmd /C exit /b 0
-)
-
-echo.
-if errorlevel 1 (
-    echo.Build failed (exit code %ERRORLEVEL%^), check for error messages
-    echo.above.  Any output will be found in %BUILDDIR%\%1
-) else (
-    echo.Build succeeded. All output should be in %BUILDDIR%\%1
-)
-goto end
-
-:htmlview
-if NOT "%2" EQU "" (
-    echo.Can't specify filenames to build with htmlview target, ignoring.
-)
-cmd /C %this% html
-
-if EXIST %BUILDDIR%\html\index.html (
-    echo.Opening %BUILDDIR%\html\index.html in the default web browser...
-    start %BUILDDIR%\html\index.html
-)
-
-goto end
-
-:check
-cmd /C %PYTHON% tools\rstlint.py -i tools
-goto end
-
-:serve
-cmd /C %PYTHON% ..\Tools\scripts\serve.py %BUILDDIR%\html
-goto end
-
-:end
-popd
+@echo off\r
+setlocal\r
+\r
+pushd %~dp0\r
+\r
+set this=%~n0\r
+\r
+if "%SPHINXBUILD%" EQU "" set SPHINXBUILD=sphinx-build\r
+if "%PYTHON%" EQU "" set PYTHON=py\r
+\r
+if DEFINED ProgramFiles(x86) set _PRGMFLS=%ProgramFiles(x86)%\r
+if NOT DEFINED ProgramFiles(x86) set _PRGMFLS=%ProgramFiles%\r
+if "%HTMLHELP%" EQU "" set HTMLHELP=%_PRGMFLS%\HTML Help Workshop\hhc.exe\r
+\r
+if "%DISTVERSION%" EQU "" for /f "usebackq" %%v in (`%PYTHON% tools/extensions/patchlevel.py`) do set DISTVERSION=%%v\r
+\r
+if "%BUILDDIR%" EQU "" set BUILDDIR=build\r
+\r
+rem Targets that don't require sphinx-build\r
+if "%1" EQU "" goto help\r
+if "%1" EQU "help" goto help\r
+if "%1" EQU "check" goto check\r
+if "%1" EQU "serve" goto serve\r
+if "%1" == "clean" (\r
+    rmdir /q /s %BUILDDIR%\r
+    goto end\r
+)\r
+\r
+%SPHINXBUILD% 2> nul\r
+if errorlevel 9009 (\r
+    echo.\r
+    echo.The 'sphinx-build' command was not found. Make sure you have Sphinx\r
+    echo.installed, then set the SPHINXBUILD environment variable to point\r
+    echo.to the full path of the 'sphinx-build' executable. Alternatively you\r
+    echo.may add the Sphinx directory to PATH.\r
+    echo.\r
+    echo.If you don't have Sphinx installed, grab it from\r
+    echo.http://sphinx-doc.org/\r
+    goto end\r
+)\r
+\r
+rem Targets that do require sphinx-build and have their own label\r
+if "%1" EQU "htmlview" goto htmlview\r
+\r
+rem Everything else\r
+goto build\r
+\r
+:help\r
+echo.usage: %this% BUILDER [filename ...]\r
+echo.\r
+echo.Call %this% with the desired Sphinx builder as the first argument, e.g.\r
+echo.``%this% html`` or ``%this% doctest``.  Interesting targets that are\r
+echo.always available include:\r
+echo.\r
+echo.   Provided by Sphinx:\r
+echo.      html, htmlhelp, latex, text\r
+echo.      suspicious, linkcheck, changes, doctest\r
+echo.   Provided by this script:\r
+echo.      clean, check, serve, htmlview\r
+echo.\r
+echo.All arguments past the first one are passed through to sphinx-build as\r
+echo.filenames to build or are ignored.  See README.txt in this directory or\r
+echo.the documentation for your version of Sphinx for more exhaustive lists\r
+echo.of available targets and descriptions of each.\r
+echo.\r
+echo.This script assumes that the SPHINXBUILD environment variable contains\r
+echo.a legitimate command for calling sphinx-build, or that sphinx-build is\r
+echo.on your PATH if SPHINXBUILD is not set.  Options for sphinx-build can\r
+echo.be passed by setting the SPHINXOPTS environment variable.\r
+goto end\r
+\r
+:build\r
+if NOT "%PAPER%" == "" (\r
+    set SPHINXOPTS=-D latex_paper_size=%PAPER% %SPHINXOPTS%\r
+)\r
+cmd /C %SPHINXBUILD% %SPHINXOPTS% -b%1 -dbuild\doctrees . %BUILDDIR%\%*\r
+\r
+if "%1" EQU "htmlhelp" (\r
+    if  not exist "%HTMLHELP%" (\r
+        echo.\r
+        echo.The HTML Help Workshop was not found.  Set the HTMLHELP variable\r
+        echo.to the path to hhc.exe or download and install it from\r
+        echo.http://msdn.microsoft.com/en-us/library/ms669985\r
+        rem Set errorlevel to 1 and exit\r
+        cmd /C exit /b 1\r
+        goto end\r
+    )\r
+    cmd /C "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp\r
+    rem hhc.exe seems to always exit with code 1, reset to 0 for less than 2\r
+    if not errorlevel 2 cmd /C exit /b 0\r
+)\r
+\r
+echo.\r
+if errorlevel 1 (\r
+    echo.Build failed (exit code %ERRORLEVEL%^), check for error messages\r
+    echo.above.  Any output will be found in %BUILDDIR%\%1\r
+) else (\r
+    echo.Build succeeded. All output should be in %BUILDDIR%\%1\r
+)\r
+goto end\r
+\r
+:htmlview\r
+if NOT "%2" EQU "" (\r
+    echo.Can't specify filenames to build with htmlview target, ignoring.\r
+)\r
+cmd /C %this% html\r
+\r
+if EXIST %BUILDDIR%\html\index.html (\r
+    echo.Opening %BUILDDIR%\html\index.html in the default web browser...\r
+    start %BUILDDIR%\html\index.html\r
+)\r
+\r
+goto end\r
+\r
+:check\r
+cmd /C %PYTHON% tools\rstlint.py -i tools\r
+goto end\r
+\r
+:serve\r
+cmd /C %PYTHON% ..\Tools\scripts\serve.py %BUILDDIR%\html\r
+goto end\r
+\r
+:end\r
+popd\r
index 206853b..c61c55b 100644 (file)
@@ -1225,13 +1225,17 @@ Basic customization
 
    .. index:: pair: class; constructor
 
-   Called when the instance is created.  The arguments are those passed to the
+   Called after the instance has been created (by :meth:`__new__`), but before
+   it is returned to the caller.  The arguments are those passed to the
    class constructor expression.  If a base class has an :meth:`__init__` method,
    the derived class's :meth:`__init__` method, if any, must explicitly call it to
    ensure proper initialization of the base class part of the instance; for
-   example: ``BaseClass.__init__(self, [args...])``.  As a special constraint on
-   constructors, no value may be returned; doing so will cause a :exc:`TypeError`
-   to be raised at runtime.
+   example: ``BaseClass.__init__(self, [args...])``.
+
+   Because :meth:`__new__` and :meth:`__init__` work together in constructing
+   objects (:meth:`__new__` to create it, and :meth:`__init__` to customise it),
+   no non-``None`` value may be returned by :meth:`__init__`; doing so will
+   cause a :exc:`TypeError` to be raised at runtime.
 
 
 .. method:: object.__del__(self)
@@ -1904,6 +1908,12 @@ sequences, it should iterate through the values.
       indexes to allow proper detection of the end of the sequence.
 
 
+.. method:: object.__missing__(self, key)
+
+   Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses
+   when key is not in the dictionary.
+
+
 .. method:: object.__setitem__(self, key, value)
 
    Called to implement assignment to ``self[key]``.  Same note as for
@@ -1983,15 +1993,15 @@ objects.  Immutable sequences methods should at most only define
       :meth:`__getslice__`.  Therefore, you have to override it in derived
       classes when implementing slicing.)
 
-   Called to implement evaluation of ``self[i:j]``. The returned object should be
-   of the same type as *self*.  Note that missing *i* or *j* in the slice
-   expression are replaced by zero or ``sys.maxint``, respectively.  If negative
-   indexes are used in the slice, the length of the sequence is added to that
-   index. If the instance does not implement the :meth:`__len__` method, an
-   :exc:`AttributeError` is raised. No guarantee is made that indexes adjusted this
-   way are not still negative.  Indexes which are greater than the length of the
-   sequence are not modified. If no :meth:`__getslice__` is found, a slice object
-   is created instead, and passed to :meth:`__getitem__` instead.
+   Called to implement evaluation of ``self[i:j]``. The returned object should
+   be of the same type as *self*.  Note that missing *i* or *j* in the slice
+   expression are replaced by zero or :attr:`sys.maxsize`, respectively.  If
+   negative indexes are used in the slice, the length of the sequence is added
+   to that index. If the instance does not implement the :meth:`__len__` method,
+   an :exc:`AttributeError` is raised. No guarantee is made that indexes
+   adjusted this way are not still negative.  Indexes which are greater than the
+   length of the sequence are not modified. If no :meth:`__getslice__` is found,
+   a slice object is created instead, and passed to :meth:`__getitem__` instead.
 
 
 .. method:: object.__setslice__(self, i, j, sequence)
index 21c3db2..85a4318 100644 (file)
@@ -306,7 +306,7 @@ dd {
     margin-left: 30px;
 }
 
-dt:target, .highlight {
+dt:target, .highlighted {
     background-color: #fbe54e;
 }
 
index 2d79a00..89589bc 100644 (file)
@@ -179,9 +179,9 @@ There are three built-in functions that are very useful when used with lists:
 
 ``filter(function, sequence)`` returns a sequence consisting of those items from
 the sequence for which ``function(item)`` is true. If *sequence* is a
-:class:`string` or :class:`tuple`, the result will be of the same type;
-otherwise, it is always a :class:`list`. For example, to compute a sequence of
-numbers divisible by 3 or 5::
+:class:`str`, :class:`unicode` or :class:`tuple`, the result will be of the
+same type; otherwise, it is always a :class:`list`.  For example, to compute a
+sequence of numbers divisible by 3 or 5::
 
    >>> def f(x): return x % 3 == 0 or x % 5 == 0
    ...
index 514c5f1..67f927f 100644 (file)
@@ -62,6 +62,8 @@ 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.
 
+All command-line options are described in :ref:`using-on-general`.
+
 
 .. _tut-argpassing:
 
@@ -138,7 +140,7 @@ encodings can be found in the Python Library Reference, in the section on
 For example, to write Unicode literals including the Euro currency symbol, the
 ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value
 164.  This script, when saved in the ISO-8859-15 encoding, will print the value
-8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit::
+8364 (the Unicode code point corresponding to the Euro symbol) and then exit::
 
    # -*- coding: iso-8859-15 -*-
 
index d30b194..e5ced49 100644 (file)
@@ -170,7 +170,7 @@ and special characters::
    >>> print '"Isn\'t," she said.'
    "Isn't," she said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
-   >>> s  # without print(), \n is included in the output
+   >>> s  # without print, \n is included in the output
    'First line.\nSecond line.'
    >>> print s  # with print, \n produces a new line
    First line.
@@ -309,7 +309,7 @@ indices, if both are within bounds.  For example, the length of ``word[1:3]`` is
 
 Attempting to use a index that is too large will result in an error::
 
-   >>> word[42]  # the word only has 7 characters
+   >>> word[42]  # the word only has 6 characters
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: string index out of range
index b657f3f..ce5e76f 100644 (file)
@@ -1,7 +1,7 @@
-.. highlightlang:: none
+.. highlightlang:: sh
 
 .. ATTENTION: You probably should update Misc/python.man, too, if you modify
-.. this file.
+   this file.
 
 .. _using-on-general:
 
@@ -130,6 +130,10 @@ source.
    ``"-"`` and the current directory will be added to the start of
    :data:`sys.path`.
 
+   .. seealso::
+      :func:`runpy.run_path`
+         Equivalent functionality directly available to Python code
+
 
 .. describe:: <script>
 
index eaf66eb..a71efde 100644 (file)
 /*--start constants--*/
 #define PY_MAJOR_VERSION       2
 #define PY_MINOR_VERSION       7
-#define PY_MICRO_VERSION       9
+#define PY_MICRO_VERSION       10
 #define PY_RELEASE_LEVEL       PY_RELEASE_LEVEL_FINAL
 #define PY_RELEASE_SERIAL      0
 
 /* Version as a string */
-#define PY_VERSION             "2.7.9"
+#define PY_VERSION             "2.7.10"
 /*--end constants--*/
 
 /* Subversion Revision number of this file (not of the repository). Empty
index dbe3bfa..2ef205e 100644 (file)
@@ -91,6 +91,7 @@ PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
 PyAPI_FUNC(int) PyErr_GivenExceptionMatches(PyObject *, PyObject *);
 PyAPI_FUNC(int) PyErr_ExceptionMatches(PyObject *);
 PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**);
+PyAPI_FUNC(void) _PyErr_ReplaceException(PyObject *, PyObject *, PyObject *);
 
 /* */
 
diff --git a/LICENSE b/LICENSE
index f9ca2c9..88251f5 100644 (file)
--- a/LICENSE
+++ b/LICENSE
@@ -74,8 +74,8 @@ 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,
-2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are retained
-in Python alone or in any derivative version prepared by Licensee.
+2011, 2012, 2013, 2014, 2015 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
index 0b15531..b1704d9 100644 (file)
@@ -528,12 +528,13 @@ class Morsel(dict):
 # result, the parsing rules here are less strict.
 #
 
-_LegalCharsPatt  = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"
+_LegalKeyChars  = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
+_LegalValueChars = _LegalKeyChars + r"\[\]"
 _CookiePattern = re.compile(
     r"(?x)"                       # This is a Verbose pattern
     r"\s*"                        # Optional whitespace at start of cookie
     r"(?P<key>"                   # Start of group 'key'
-    ""+ _LegalCharsPatt +"+?"     # Any word of at least one letter, nongreedy
+    "["+ _LegalKeyChars +"]+?"     # Any word of at least one letter, nongreedy
     r")"                          # End of group 'key'
     r"("                          # Optional group: there may not be a value.
     r"\s*=\s*"                    # Equal Sign
@@ -542,7 +543,7 @@ _CookiePattern = re.compile(
     r"|"                            # or
     r"\w{3},\s[\s\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr
     r"|"                            # or
-    ""+ _LegalCharsPatt +"*"        # Any word or empty string
+    "["+ _LegalValueChars +"]*"        # Any word or empty string
     r")"                          # End of group 'val'
     r")?"                         # End of optional value group
     r"\s*"                        # Any number of spaces.
index d497e1e..783d0ac 100644 (file)
@@ -14,6 +14,7 @@ import os
 import posixpath
 import BaseHTTPServer
 import urllib
+import urlparse
 import cgi
 import sys
 import shutil
@@ -68,10 +69,14 @@ class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
         path = self.translate_path(self.path)
         f = None
         if os.path.isdir(path):
-            if not self.path.endswith('/'):
+            parts = urlparse.urlsplit(self.path)
+            if not parts.path.endswith('/'):
                 # redirect browser - doing basically what apache does
                 self.send_response(301)
-                self.send_header("Location", self.path + "/")
+                new_parts = (parts[0], parts[1], parts[2] + '/',
+                             parts[3], parts[4])
+                new_url = urlparse.urlunsplit(new_parts)
+                self.send_header("Location", new_url)
                 self.end_headers()
                 return None
             for index in "index.html", "index.htm":
index 90cc633..a446aeb 100644 (file)
@@ -18,7 +18,7 @@ from cookielib import (_warn_unhandled_exception, FileCookieJar, LoadError,
                        iso2time, time2isoz)
 
 def lwp_cookie_str(cookie):
-    """Return string representation of Cookie in an the LWP cookie file format.
+    """Return string representation of Cookie in the LWP cookie file format.
 
     Actually, the format is extended a bit -- see module docstring.
 
index 3d567e3..0385627 100644 (file)
@@ -548,23 +548,25 @@ class MutableMapping(Mapping):
             If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
             In either case, this is followed by: for k, v in F.items(): D[k] = v
         '''
-        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)")
+        if not args:
+            raise TypeError("descriptor 'update' of 'MutableMapping' object "
+                            "needs an argument")
         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
+        args = args[1:]
+        if len(args) > 1:
+            raise TypeError('update expected at most 1 arguments, got %d' %
+                            len(args))
+        if args:
+            other = args[0]
+            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
 
index 3acbc65..a7f4301 100644 (file)
@@ -25,8 +25,8 @@ __metaclass__ = type
 DEFAULT_BUFFER_SIZE = 8 * 1024  # bytes
 
 # NOTE: Base classes defined here are registered with the "official" ABCs
-# defined in io.py. We don't use real inheritance though, because we don't
-# want to inherit the C implementations.
+# defined in io.py. We don't use real inheritance though, because we don't want
+# to inherit the C implementations.
 
 
 class BlockingIOError(IOError):
@@ -775,7 +775,7 @@ class _BufferedIOMixin(BufferedIOBase):
         clsname = self.__class__.__name__
         try:
             name = self.name
-        except AttributeError:
+        except Exception:
             return "<_pyio.{0}>".format(clsname)
         else:
             return "<_pyio.{0} name={1!r}>".format(clsname, name)
@@ -1216,8 +1216,10 @@ class BufferedRWPair(BufferedIOBase):
         return self.writer.flush()
 
     def close(self):
-        self.writer.close()
-        self.reader.close()
+        try:
+            self.writer.close()
+        finally:
+            self.reader.close()
 
     def isatty(self):
         return self.reader.isatty() or self.writer.isatty()
@@ -1538,7 +1540,7 @@ class TextIOWrapper(TextIOBase):
     def __repr__(self):
         try:
             name = self.name
-        except AttributeError:
+        except Exception:
             return "<_pyio.TextIOWrapper encoding='{0}'>".format(self.encoding)
         else:
             return "<_pyio.TextIOWrapper name={0!r} encoding='{1}'>".format(
index 042db6f..1bd570d 100644 (file)
@@ -335,9 +335,9 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
     # though
     week_of_year = -1
     week_of_year_start = -1
-    # weekday and julian defaulted to -1 so as to signal need to calculate
+    # weekday and julian defaulted to None so as to signal need to calculate
     # values
-    weekday = julian = -1
+    weekday = julian = None
     found_dict = found.groupdict()
     for group_key in found_dict.iterkeys():
         # Directives not explicitly handled below:
@@ -434,14 +434,14 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
         year = 1900
     # If we know the week of the year and what day of that week, we can figure
     # out the Julian day of the year.
-    if julian == -1 and week_of_year != -1 and weekday != -1:
+    if julian is None and week_of_year != -1 and weekday is not None:
         week_starts_Mon = True if week_of_year_start == 0 else False
         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
                                             week_starts_Mon)
     # Cannot pre-calculate datetime_date() since can change in Julian
     # calculation and thus could have different value for the day of the week
     # calculation.
-    if julian == -1:
+    if julian is None:
         # Need to add 1 to result since first day of the year is 1, not 0.
         julian = datetime_date(year, month, day).toordinal() - \
                   datetime_date(year, 1, 1).toordinal() + 1
@@ -451,7 +451,7 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
         year = datetime_result.year
         month = datetime_result.month
         day = datetime_result.day
-    if weekday == -1:
+    if weekday is None:
         weekday = datetime_date(year, month, day).weekday()
     if leap_year_fix:
         # the caller didn't supply a year but asked for Feb 29th. We couldn't
index 9ac710f..c9a021e 100644 (file)
@@ -357,10 +357,13 @@ class Aifc_read:
         self._soundpos = 0
 
     def close(self):
-        if self._decomp:
-            self._decomp.CloseDecompressor()
-            self._decomp = None
-        self._file.close()
+        decomp = self._decomp
+        try:
+            if decomp:
+                self._decomp = None
+                decomp.CloseDecompressor()
+        finally:
+            self._file.close()
 
     def tell(self):
         return self._soundpos
index 8abc9f3..14ec233 100644 (file)
@@ -32,7 +32,8 @@ class Error(Exception):
     pass
 
 # States (what have we written)
-[_DID_HEADER, _DID_DATA, _DID_RSRC] = range(3)
+_DID_HEADER = 0
+_DID_DATA = 1
 
 # Various constants
 REASONABLY_LARGE=32768  # Minimal amount we pass the rle-coder
@@ -235,17 +236,22 @@ class BinHex:
         self._write(data)
 
     def close(self):
-        if self.state < _DID_DATA:
-            self.close_data()
-        if self.state != _DID_DATA:
-            raise Error, 'Close at the wrong time'
-        if self.rlen != 0:
-            raise Error, \
-                  "Incorrect resource-datasize, diff=%r" % (self.rlen,)
-        self._writecrc()
-        self.ofp.close()
-        self.state = None
-        del self.ofp
+        if self.state is None:
+            return
+        try:
+            if self.state < _DID_DATA:
+                self.close_data()
+            if self.state != _DID_DATA:
+                raise Error, 'Close at the wrong time'
+            if self.rlen != 0:
+                raise Error, \
+                    "Incorrect resource-datasize, diff=%r" % (self.rlen,)
+            self._writecrc()
+        finally:
+            self.state = None
+            ofp = self.ofp
+            del self.ofp
+            ofp.close()
 
 def binhex(inp, out):
     """(infilename, outfilename) - Create binhex-encoded copy of a file"""
@@ -463,11 +469,15 @@ class HexBin:
         return self._read(n)
 
     def close(self):
-        if self.rlen:
-            dummy = self.read_rsrc(self.rlen)
-        self._checkcrc()
-        self.state = _DID_RSRC
-        self.ifp.close()
+        if self.state is None:
+            return
+        try:
+            if self.rlen:
+                dummy = self.read_rsrc(self.rlen)
+            self._checkcrc()
+        finally:
+            self.state = None
+            self.ifp.close()
 
 def hexbin(inp, out):
     """(infilename, outfilename) - Decode binhexed file"""
index caef1ac..004e357 100644 (file)
@@ -412,9 +412,6 @@ if sys.version_info[0] >= 3 :
         def get_dbp(self) :
             return self._db
 
-    import string
-    string.letters=[chr(i) for i in xrange(65,91)]
-
     bsddb._db.DBEnv_orig = bsddb._db.DBEnv
     bsddb._db.DB_orig = bsddb._db.DB
     if bsddb.db.version() <= (4, 3) :
index 3c57be4..1459d36 100644 (file)
@@ -999,7 +999,7 @@ class BasicMultiDBTestCase(BasicTestCase):
         for x in "The quick brown fox jumped over the lazy dog".split():
             d2.put(x, self.makeData(x))
 
-        for x in string.letters:
+        for x in string.ascii_letters:
             d3.put(x, x*70)
 
         d1.sync()
@@ -1047,7 +1047,7 @@ class BasicMultiDBTestCase(BasicTestCase):
             if verbose:
                 print rec
             rec = c3.next()
-        self.assertEqual(count, len(string.letters))
+        self.assertEqual(count, len(string.ascii_letters))
 
 
         c1.close()
index c3701e1..e5609c5 100644 (file)
@@ -59,7 +59,7 @@ class DBShelveTestCase(unittest.TestCase):
             return bytes(key, "iso8859-1")  # 8 bits
 
     def populateDB(self, d):
-        for x in string.letters:
+        for x in string.ascii_letters:
             d[self.mk('S' + x)] = 10 * x           # add a string
             d[self.mk('I' + x)] = ord(x)           # add an integer
             d[self.mk('L' + x)] = [x] * 10         # add a list
index 8763b54..541044c 100644 (file)
@@ -26,14 +26,14 @@ class GetReturnsNoneTestCase(unittest.TestCase):
         d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
         d.set_get_returns_none(1)
 
-        for x in string.letters:
+        for x in string.ascii_letters:
             d.put(x, x * 40)
 
         data = d.get('bad key')
         self.assertEqual(data, None)
 
-        data = d.get(string.letters[0])
-        self.assertEqual(data, string.letters[0]*40)
+        data = d.get(string.ascii_letters[0])
+        self.assertEqual(data, string.ascii_letters[0]*40)
 
         count = 0
         c = d.cursor()
@@ -43,7 +43,7 @@ class GetReturnsNoneTestCase(unittest.TestCase):
             rec = c.next()
 
         self.assertEqual(rec, None)
-        self.assertEqual(count, len(string.letters))
+        self.assertEqual(count, len(string.ascii_letters))
 
         c.close()
         d.close()
@@ -54,14 +54,14 @@ class GetReturnsNoneTestCase(unittest.TestCase):
         d.open(self.filename, db.DB_BTREE, db.DB_CREATE)
         d.set_get_returns_none(0)
 
-        for x in string.letters:
+        for x in string.ascii_letters:
             d.put(x, x * 40)
 
         self.assertRaises(db.DBNotFoundError, d.get, 'bad key')
         self.assertRaises(KeyError, d.get, 'bad key')
 
-        data = d.get(string.letters[0])
-        self.assertEqual(data, string.letters[0]*40)
+        data = d.get(string.ascii_letters[0])
+        self.assertEqual(data, string.ascii_letters[0]*40)
 
         count = 0
         exceptionHappened = 0
@@ -77,7 +77,7 @@ class GetReturnsNoneTestCase(unittest.TestCase):
 
         self.assertNotEqual(rec, None)
         self.assertTrue(exceptionHappened)
-        self.assertEqual(count, len(string.letters))
+        self.assertEqual(count, len(string.ascii_letters))
 
         c.close()
         d.close()
index d3a0c8b..5fa22ee 100644 (file)
@@ -10,7 +10,6 @@ from test_all import db, verbose, get_new_database_path
 
 #----------------------------------------------------------------------
 
-@unittest.skip("fails on Windows; see issue 22943")
 class SimpleQueueTestCase(unittest.TestCase):
     def setUp(self):
         self.filename = get_new_database_path()
@@ -37,17 +36,17 @@ class SimpleQueueTestCase(unittest.TestCase):
             print "before appends" + '-' * 30
             pprint(d.stat())
 
-        for x in string.letters:
+        for x in string.ascii_letters:
             d.append(x * 40)
 
-        self.assertEqual(len(d), len(string.letters))
+        self.assertEqual(len(d), len(string.ascii_letters))
 
         d.put(100, "some more data")
         d.put(101, "and some more ")
         d.put(75,  "out of order")
         d.put(1,   "replacement data")
 
-        self.assertEqual(len(d), len(string.letters)+3)
+        self.assertEqual(len(d), len(string.ascii_letters)+3)
 
         if verbose:
             print "before close" + '-' * 30
@@ -108,17 +107,17 @@ class SimpleQueueTestCase(unittest.TestCase):
             print "before appends" + '-' * 30
             pprint(d.stat())
 
-        for x in string.letters:
+        for x in string.ascii_letters:
             d.append(x * 40)
 
-        self.assertEqual(len(d), len(string.letters))
+        self.assertEqual(len(d), len(string.ascii_letters))
 
         d.put(100, "some more data")
         d.put(101, "and some more ")
         d.put(75,  "out of order")
         d.put(1,   "replacement data")
 
-        self.assertEqual(len(d), len(string.letters)+3)
+        self.assertEqual(len(d), len(string.ascii_letters)+3)
 
         if verbose:
             print "before close" + '-' * 30
index fb6956a..b0e30de 100644 (file)
@@ -4,12 +4,11 @@
 import os, sys
 import errno
 from pprint import pprint
+import string
 import unittest
 
 from test_all import db, test_support, verbose, get_new_environment_path, get_new_database_path
 
-letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
-
 
 #----------------------------------------------------------------------
 
@@ -39,7 +38,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
 
         d.open(self.filename, db.DB_RECNO, db.DB_CREATE)
 
-        for x in letters:
+        for x in string.ascii_letters:
             recno = d.append(x * 60)
             self.assertIsInstance(recno, int)
             self.assertGreaterEqual(recno, 1)
@@ -270,7 +269,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
         d.set_re_pad(45)  # ...test both int and char
         d.open(self.filename, db.DB_RECNO, db.DB_CREATE)
 
-        for x in letters:
+        for x in string.ascii_letters:
             d.append(x * 35)    # These will be padded
 
         d.append('.' * 40)      # this one will be exact
index a8fbc10..3e3b5a4 100644 (file)
@@ -85,8 +85,10 @@ class Chunk:
 
     def close(self):
         if not self.closed:
-            self.skip()
-            self.closed = True
+            try:
+                self.skip()
+            finally:
+                self.closed = True
 
     def isatty(self):
         if self.closed:
index 93c16c3..049a3f0 100644 (file)
@@ -20,8 +20,14 @@ __all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE",
            "BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",
            "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE",
            "BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE",
+           "CodecInfo", "Codec", "IncrementalEncoder", "IncrementalDecoder",
+           "StreamReader", "StreamWriter",
+           "StreamReaderWriter", "StreamRecoder",
+           "getencoder", "getdecoder", "getincrementalencoder",
+           "getincrementaldecoder", "getreader", "getwriter",
+           "encode", "decode", "iterencode", "iterdecode",
            "strict_errors", "ignore_errors", "replace_errors",
-           "xmlcharrefreplace_errors",
+           "xmlcharrefreplace_errors", "backslashreplace_errors",
            "register_error", "lookup_error"]
 
 ### Constants
@@ -1051,7 +1057,7 @@ def make_encoding_map(decoding_map):
         during translation.
 
         One example where this happens is cp875.py which decodes
-        multiple character to \u001a.
+        multiple character to \\u001a.
 
     """
     m = {}
index 8831f0b..1dcd233 100644 (file)
@@ -35,12 +35,17 @@ class OrderedDict(dict):
     # The sentinel element never gets deleted (this simplifies the algorithm).
     # Each link is stored as a list of length three:  [PREV, NEXT, KEY].
 
-    def __init__(self, *args, **kwds):
+    def __init__(*args, **kwds):
         '''Initialize an ordered dictionary.  The signature is the same as
         regular dictionaries, but keyword arguments are not recommended because
         their insertion order is arbitrary.
 
         '''
+        if not args:
+            raise TypeError("descriptor '__init__' of 'OrderedDict' object "
+                            "needs an argument")
+        self = args[0]
+        args = args[1:]
         if len(args) > 1:
             raise TypeError('expected at most 1 arguments, got %d' % len(args))
         try:
@@ -438,7 +443,7 @@ class Counter(dict):
     #   http://code.activestate.com/recipes/259174/
     #   Knuth, TAOCP Vol. II section 4.6.3
 
-    def __init__(self, iterable=None, **kwds):
+    def __init__(*args, **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.
@@ -449,8 +454,15 @@ class Counter(dict):
         >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
 
         '''
+        if not args:
+            raise TypeError("descriptor '__init__' of 'Counter' object "
+                            "needs an argument")
+        self = args[0]
+        args = args[1:]
+        if len(args) > 1:
+            raise TypeError('expected at most 1 arguments, got %d' % len(args))
         super(Counter, self).__init__()
-        self.update(iterable, **kwds)
+        self.update(*args, **kwds)
 
     def __missing__(self, key):
         'The count of elements not in the Counter is zero.'
@@ -501,7 +513,7 @@ class Counter(dict):
         raise NotImplementedError(
             'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')
 
-    def update(self, iterable=None, **kwds):
+    def update(*args, **kwds):
         '''Like dict.update() but add counts instead of replacing them.
 
         Source can be an iterable, a dictionary, or another Counter instance.
@@ -521,6 +533,14 @@ class Counter(dict):
         # contexts.  Instead, we implement straight-addition.  Both the inputs
         # and outputs are allowed to contain zero and negative counts.
 
+        if not args:
+            raise TypeError("descriptor 'update' of 'Counter' object "
+                            "needs an argument")
+        self = args[0]
+        args = args[1:]
+        if len(args) > 1:
+            raise TypeError('expected at most 1 arguments, got %d' % len(args))
+        iterable = args[0] if args else None
         if iterable is not None:
             if isinstance(iterable, Mapping):
                 if self:
@@ -536,7 +556,7 @@ class Counter(dict):
         if kwds:
             self.update(kwds)
 
-    def subtract(self, iterable=None, **kwds):
+    def subtract(*args, **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.
@@ -552,6 +572,14 @@ class Counter(dict):
         -1
 
         '''
+        if not args:
+            raise TypeError("descriptor 'subtract' of 'Counter' object "
+                            "needs an argument")
+        self = args[0]
+        args = args[1:]
+        if len(args) > 1:
+            raise TypeError('expected at most 1 arguments, got %d' % len(args))
+        iterable = args[0] if args else None
         if iterable is not None:
             self_get = self.get
             if isinstance(iterable, Mapping):
index f260bc5..f2df467 100644 (file)
@@ -464,26 +464,42 @@ def parse_ns_headers(ns_headers):
     for ns_header in ns_headers:
         pairs = []
         version_set = False
-        for ii, param in enumerate(re.split(r";\s*", ns_header)):
-            param = param.rstrip()
-            if param == "": continue
-            if "=" not in param:
-                k, v = param, None
-            else:
-                k, v = re.split(r"\s*=\s*", param, 1)
-                k = k.lstrip()
+
+        # XXX: The following does not strictly adhere to RFCs in that empty
+        # names and values are legal (the former will only appear once and will
+        # be overwritten if multiple occurrences are present). This is
+        # mostly to deal with backwards compatibility.
+        for ii, param in enumerate(ns_header.split(';')):
+            param = param.strip()
+
+            key, sep, val = param.partition('=')
+            key = key.strip()
+
+            if not key:
+                if ii == 0:
+                    break
+                else:
+                    continue
+
+            # allow for a distinction between present and empty and missing
+            # altogether
+            val = val.strip() if sep else None
+
             if ii != 0:
-                lc = k.lower()
+                lc = key.lower()
                 if lc in known_attrs:
-                    k = lc
-                if k == "version":
+                    key = lc
+
+                if key == "version":
                     # This is an RFC 2109 cookie.
-                    v = _strip_quotes(v)
+                    if val is not None:
+                        val = _strip_quotes(val)
                     version_set = True
-                if k == "expires":
+                elif key == "expires":
                     # convert expires date to seconds since epoch
-                    v = http2time(_strip_quotes(v))  # None if invalid
-            pairs.append((k, v))
+                    if val is not None:
+                        val = http2time(_strip_quotes(val))  # None if invalid
+            pairs.append((key, val))
 
         if pairs:
             if not version_set:
index f9e1c0d..f474d5c 100644 (file)
@@ -1 +1 @@
-svn export --force http://svn.red-bean.com/bob/macholib/trunk/macholib/ .
+svn export --force http://svn.red-bean.com/bob/macholib/trunk/macholib/ .\r
index c5f6ace..e7a0a93 100644 (file)
@@ -32,15 +32,24 @@ class Test_OpenGL_libs(unittest.TestCase):
     def setUp(self):
         self.gl = self.glu = self.gle = None
         if lib_gl:
-            self.gl = CDLL(lib_gl, mode=RTLD_GLOBAL)
+            try:
+                self.gl = CDLL(lib_gl, mode=RTLD_GLOBAL)
+            except OSError:
+                pass
         if lib_glu:
-            self.glu = CDLL(lib_glu, RTLD_GLOBAL)
+            try:
+                self.glu = CDLL(lib_glu, RTLD_GLOBAL)
+            except OSError:
+                pass
         if lib_gle:
             try:
                 self.gle = CDLL(lib_gle)
             except OSError:
                 pass
 
+    def tearDown(self):
+        self.gl = self.glu = self.gle = None
+
     @unittest.skipUnless(lib_gl, 'lib_gl not available')
     def test_gl(self):
         if self.gl:
index 136cbe9..73528d4 100644 (file)
@@ -14,9 +14,9 @@ class X(Structure):
 class Y(X):
     _fields_ = [("str", c_char_p)]
 
-class PickleTest(unittest.TestCase):
+class PickleTest:
     def dumps(self, item):
-        return pickle.dumps(item)
+        return pickle.dumps(item, self.proto)
 
     def loads(self, item):
         return pickle.loads(item)
@@ -67,17 +67,15 @@ class PickleTest(unittest.TestCase):
             self.assertRaises(ValueError, lambda: self.dumps(item))
 
     def test_wchar(self):
-        pickle.dumps(c_char("x"))
+        self.dumps(c_char(b"x"))
         # Issue 5049
-        pickle.dumps(c_wchar(u"x"))
+        self.dumps(c_wchar(u"x"))
 
-class PickleTest_1(PickleTest):
-    def dumps(self, item):
-        return pickle.dumps(item, 1)
-
-class PickleTest_2(PickleTest):
-    def dumps(self, item):
-        return pickle.dumps(item, 2)
+for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+    name = 'PickleTest_%s' % proto
+    globals()[name] = type(name,
+                           (PickleTest, unittest.TestCase),
+                           {'proto': proto})
 
 if __name__ == "__main__":
     unittest.main()
index 3e74791..5cdde68 100644 (file)
@@ -7,8 +7,6 @@ ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
                  c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float]
 python_types = [int, int, int, int, int, long,
                 int, long, long, long, float, float]
-LargeNamedType = type('T' * 2 ** 25, (Structure,), {})
-large_string = 'T' * 2 ** 25
 
 class PointersTestCase(unittest.TestCase):
 
@@ -191,9 +189,11 @@ class PointersTestCase(unittest.TestCase):
             self.assertEqual(bool(mth), True)
 
     def test_pointer_type_name(self):
+        LargeNamedType = type('T' * 2 ** 25, (Structure,), {})
         self.assertTrue(POINTER(LargeNamedType))
 
     def test_pointer_type_str_name(self):
+        large_string = 'T' * 2 ** 25
         self.assertTrue(POINTER(large_string))
 
 if __name__ == '__main__':
index fe0ed0a..1e882e3 100644 (file)
@@ -177,7 +177,7 @@ elif os.name == "posix":
             res = re.findall(expr, data)
             if not res:
                 return _get_soname(_findLib_gcc(name))
-            res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y)))
+            res.sort(key=_num_version)
             return res[-1]
 
     elif sys.platform == "sunos5":
index 8780be7..0370896 100644 (file)
@@ -15,5 +15,5 @@ __revision__ = "$Id$"
 # Updated automatically by the Python release process.
 #
 #--start constants--
-__version__ = "2.7.9"
+__version__ = "2.7.10"
 #--end constants--
index 152bf0d..4ea03d3 100644 (file)
@@ -126,7 +126,7 @@ class check(Command):
         """Returns warnings when the provided data doesn't compile."""
         source_path = StringIO()
         parser = Parser()
-        settings = frontend.OptionParser().get_default_values()
+        settings = frontend.OptionParser(components=(Parser,)).get_default_values()
         settings.tab_width = 4
         settings.pep_references = None
         settings.rfc_references = None
@@ -142,8 +142,8 @@ class check(Command):
         document.note_source(source_path, -1)
         try:
             parser.parse(data, document)
-        except AttributeError:
-            reporter.messages.append((-1, 'Could not finish the parsing.',
-                                      '', {}))
+        except AttributeError as e:
+            reporter.messages.append(
+                (-1, 'Could not finish the parsing: %s.' % e, '', {}))
 
         return reporter.messages
index e2dc6f4..f90318e 100644 (file)
@@ -83,7 +83,7 @@ def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0):
     """Create all the empty directories under 'base_dir' needed to put 'files'
     there.
 
-    'base_dir' is just the name of a directory which doesn't necessarily
+    'base_dir' is just the name of a directory which doesn't necessarily
     exist yet; 'files' is a list of filenames to be interpreted relative to
     'base_dir'.  'base_dir' + the directory portion of every file in 'files'
     will be created if it doesn't already exist.  'mode', 'verbose' and
index f86f129..81058b1 100644 (file)
@@ -1,5 +1,6 @@
 # -*- encoding: utf8 -*-
 """Tests for distutils.command.check."""
+import textwrap
 import unittest
 from test.test_support import run_unittest
 
@@ -93,6 +94,36 @@ class CheckTestCase(support.LoggingSilencer,
         cmd = self._run(metadata, strict=1, restructuredtext=1)
         self.assertEqual(cmd._warnings, 0)
 
+    @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils")
+    def test_check_restructuredtext_with_syntax_highlight(self):
+        # Don't fail if there is a `code` or `code-block` directive
+
+        example_rst_docs = []
+        example_rst_docs.append(textwrap.dedent("""\
+            Here's some code:
+
+            .. code:: python
+
+                def foo():
+                    pass
+            """))
+        example_rst_docs.append(textwrap.dedent("""\
+            Here's some code:
+
+            .. code-block:: python
+
+                def foo():
+                    pass
+            """))
+
+        for rest_with_code in example_rst_docs:
+            pkg_info, dist = self.create_dist(long_description=rest_with_code)
+            cmd = check(dist)
+            cmd.check_restructuredtext()
+            self.assertEqual(cmd._warnings, 0)
+            msgs = cmd._check_rst_data(rest_with_code)
+            self.assertEqual(len(msgs), 0)
+
     def test_check_all(self):
 
         metadata = {'url': 'xxx', 'author': 'xxx'}
index 09a798b..690cb80 100644 (file)
@@ -124,11 +124,11 @@ class TextFile:
     def close (self):
         """Close the current file and forget everything we know about it
            (filename, current line number)."""
-
-        self.file.close ()
+        file = self.file
         self.file = None
         self.filename = None
         self.current_line = None
+        file.close()
 
 
     def gen_error (self, msg, line=None):
index 4a0c3a7..8ef7e79 100644 (file)
@@ -21,6 +21,7 @@ is read when the database is opened, and some updates rewrite the whole index)
 
 """
 
+import ast as _ast
 import os as _os
 import __builtin__
 import UserDict
@@ -85,7 +86,7 @@ class _Database(UserDict.DictMixin):
             with f:
                 for line in f:
                     line = line.rstrip()
-                    key, pos_and_siz_pair = eval(line)
+                    key, pos_and_siz_pair = _ast.literal_eval(line)
                     self._index[key] = pos_and_siz_pair
 
     # Write the index dict to the directory file.  The original directory
@@ -208,8 +209,10 @@ class _Database(UserDict.DictMixin):
         return len(self._index)
 
     def close(self):
-        self._commit()
-        self._index = self._datfile = self._dirfile = self._bakfile = None
+        try:
+            self._commit()
+        finally:
+            self._index = self._datfile = self._dirfile = self._bakfile = None
 
     __del__ = close
 
index fb03758..4b137a5 100644 (file)
@@ -84,7 +84,7 @@ def uu_decode(input,errors='strict'):
             data = a2b_uu(s)
         except binascii.Error, v:
             # Workaround for broken uuencoders by /Fredrik Lundh
-            nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3
+            nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3
             data = a2b_uu(s[:nbytes])
             #sys.stderr.write("Warning: %s\n" % str(v))
         write(data)
index 98dae76..e7df79a 100644 (file)
@@ -12,9 +12,9 @@ import tempfile
 __all__ = ["version", "bootstrap"]
 
 
-_SETUPTOOLS_VERSION = "7.0"
+_SETUPTOOLS_VERSION = "15.2"
 
-_PIP_VERSION = "1.5.6"
+_PIP_VERSION = "6.1.1"
 
 # pip currently requires ssl support, so we try to provide a nicer
 # error message when that is missing (http://bugs.python.org/issue19744)
diff --git a/Lib/ensurepip/_bundled/pip-1.5.6-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-1.5.6-py2.py3-none-any.whl
deleted file mode 100644 (file)
index 097ab43..0000000
Binary files a/Lib/ensurepip/_bundled/pip-1.5.6-py2.py3-none-any.whl and /dev/null differ
diff --git a/Lib/ensurepip/_bundled/pip-6.1.1-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-6.1.1-py2.py3-none-any.whl
new file mode 100644 (file)
index 0000000..e59694a
Binary files /dev/null and b/Lib/ensurepip/_bundled/pip-6.1.1-py2.py3-none-any.whl differ
similarity index 60%
rename from Lib/ensurepip/_bundled/setuptools-7.0-py2.py3-none-any.whl
rename to Lib/ensurepip/_bundled/setuptools-15.2-py2.py3-none-any.whl
index fa1d105..f153ed3 100644 (file)
Binary files a/Lib/ensurepip/_bundled/setuptools-7.0-py2.py3-none-any.whl and b/Lib/ensurepip/_bundled/setuptools-15.2-py2.py3-none-any.whl differ
index 21c2d1f..02dc4c6 100644 (file)
@@ -233,8 +233,10 @@ class FileInput:
         self.close()
 
     def close(self):
-        self.nextfile()
-        self._files = ()
+        try:
+            self.nextfile()
+        finally:
+            self._files = ()
 
     def __iter__(self):
         return self
@@ -270,23 +272,25 @@ class FileInput:
 
         output = self._output
         self._output = 0
-        if output:
-            output.close()
-
-        file = self._file
-        self._file = 0
-        if file and not self._isstdin:
-            file.close()
-
-        backupfilename = self._backupfilename
-        self._backupfilename = 0
-        if backupfilename and not self._backup:
-            try: os.unlink(backupfilename)
-            except OSError: pass
-
-        self._isstdin = False
-        self._buffer = []
-        self._bufindex = 0
+        try:
+            if output:
+                output.close()
+        finally:
+            file = self._file
+            self._file = 0
+            try:
+                if file and not self._isstdin:
+                    file.close()
+            finally:
+                backupfilename = self._backupfilename
+                self._backupfilename = 0
+                if backupfilename and not self._backup:
+                    try: os.unlink(backupfilename)
+                    except OSError: pass
+
+                self._isstdin = False
+                self._buffer = []
+                self._bufindex = 0
 
     def readline(self):
         try:
index ffe99b5..99002e6 100644 (file)
@@ -47,12 +47,14 @@ def filter(names, pat):
     import os,posixpath
     result=[]
     pat=os.path.normcase(pat)
-    if not pat in _cache:
+    try:
+        re_pat = _cache[pat]
+    except KeyError:
         res = translate(pat)
         if len(_cache) >= _MAXCACHE:
             _cache.clear()
-        _cache[pat] = re.compile(res)
-    match=_cache[pat].match
+        _cache[pat] = re_pat = re.compile(res)
+    match = re_pat.match
     if os.path is posixpath:
         # normcase on posix is NOP. Optimize it away from the loop.
         for name in names:
@@ -71,12 +73,14 @@ def fnmatchcase(name, pat):
     its arguments.
     """
 
-    if not pat in _cache:
+    try:
+        re_pat = _cache[pat]
+    except KeyError:
         res = translate(pat)
         if len(_cache) >= _MAXCACHE:
             _cache.clear()
-        _cache[pat] = re.compile(res)
-    return _cache[pat].match(name) is not None
+        _cache[pat] = re_pat = re.compile(res)
+    return re_pat.match(name) is not None
 
 def translate(pat):
     """Translate a shell PATTERN to a regular expression.
index c98290c..449ce71 100644 (file)
@@ -594,11 +594,16 @@ class FTP:
 
     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
+        try:
+            file = self.file
+            self.file = None
+            if file is not None:
+                file.close()
+        finally:
+            sock = self.sock
+            self.sock = None
+            if sock is not None:
+                sock.close()
 
 try:
     import ssl
@@ -638,12 +643,24 @@ else:
         '221 Goodbye.'
         >>>
         '''
-        ssl_version = ssl.PROTOCOL_TLSv1
+        ssl_version = ssl.PROTOCOL_SSLv23
 
         def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
-                     certfile=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
+                     certfile=None, context=None,
+                     timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
+            if context is not None and keyfile is not None:
+                raise ValueError("context and keyfile arguments are mutually "
+                                 "exclusive")
+            if context is not None and certfile is not None:
+                raise ValueError("context and certfile arguments are mutually "
+                                 "exclusive")
             self.keyfile = keyfile
             self.certfile = certfile
+            if context is None:
+                context = ssl._create_stdlib_context(self.ssl_version,
+                                                     certfile=certfile,
+                                                     keyfile=keyfile)
+            self.context = context
             self._prot_p = False
             FTP.__init__(self, host, user, passwd, acct, timeout)
 
@@ -656,12 +673,12 @@ else:
             '''Set up secure control connection by using TLS/SSL.'''
             if isinstance(self.sock, ssl.SSLSocket):
                 raise ValueError("Already using TLS")
-            if self.ssl_version == ssl.PROTOCOL_TLSv1:
+            if self.ssl_version >= ssl.PROTOCOL_SSLv23:
                 resp = self.voidcmd('AUTH TLS')
             else:
                 resp = self.voidcmd('AUTH SSL')
-            self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile,
-                                        ssl_version=self.ssl_version)
+            self.sock = self.context.wrap_socket(self.sock,
+                                                 server_hostname=self.host)
             self.file = self.sock.makefile(mode='rb')
             return resp
 
@@ -692,8 +709,8 @@ else:
         def ntransfercmd(self, cmd, rest=None):
             conn, size = FTP.ntransfercmd(self, cmd, rest)
             if self._prot_p:
-                conn = ssl.wrap_socket(conn, self.keyfile, self.certfile,
-                                       ssl_version=self.ssl_version)
+                conn = self.context.wrap_socket(conn,
+                                                server_hostname=self.host)
             return conn, size
 
         def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
index 7ddb94c..2648e54 100644 (file)
@@ -10,6 +10,14 @@ __all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
            'getsize', 'isdir', 'isfile']
 
 
+try:
+    _unicode = unicode
+except NameError:
+    # If Python is built without Unicode support, the unicode type
+    # will not exist. Fake one.
+    class _unicode(object):
+        pass
+
 # Does a path exist?
 # This is false for dangling symbolic links on systems that support them.
 def exists(path):
index 3f47580..43202c4 100644 (file)
@@ -52,7 +52,9 @@ from errno import ENOENT
 
 __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
            'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
-           'dgettext', 'dngettext', 'gettext', 'ngettext',
+           'bind_textdomain_codeset',
+           'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext',
+           'ldngettext', 'lngettext', 'ngettext',
            ]
 
 _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
@@ -294,11 +296,12 @@ class GNUTranslations(NullTranslations):
             # See if we're looking at GNU .mo conventions for metadata
             if mlen == 0:
                 # Catalog description
-                lastk = k = None
+                lastk = None
                 for item in tmsg.splitlines():
                     item = item.strip()
                     if not item:
                         continue
+                    k = v = None
                     if ':' in item:
                         k, v = item.split(':', 1)
                         k = k.strip().lower()
index 49566fd..de0dab1 100644 (file)
@@ -238,9 +238,9 @@ class GzipFile(io.BufferedIOBase):
             data = data.tobytes()
 
         if len(data) > 0:
-            self.size = self.size + len(data)
+            self.fileobj.write(self.compress.compress(data))
+            self.size += len(data)
             self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
-            self.fileobj.write( self.compress.compress(data) )
             self.offset += len(data)
 
         return len(data)
@@ -369,19 +369,21 @@ class GzipFile(io.BufferedIOBase):
         return self.fileobj is None
 
     def close(self):
-        if self.fileobj is None:
+        fileobj = self.fileobj
+        if fileobj is None:
             return
-        if self.mode == WRITE:
-            self.fileobj.write(self.compress.flush())
-            write32u(self.fileobj, self.crc)
-            # self.size may exceed 2GB, or even 4GB
-            write32u(self.fileobj, self.size & 0xffffffffL)
-            self.fileobj = None
-        elif self.mode == READ:
-            self.fileobj = None
-        if self.myfileobj:
-            self.myfileobj.close()
-            self.myfileobj = None
+        self.fileobj = None
+        try:
+            if self.mode == WRITE:
+                fileobj.write(self.compress.flush())
+                write32u(fileobj, self.crc)
+                # self.size may exceed 2GB, or even 4GB
+                write32u(fileobj, self.size & 0xffffffffL)
+        finally:
+            myfileobj = self.myfileobj
+            if myfileobj:
+                self.myfileobj = None
+                myfileobj.close()
 
     def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
         self._check_closed()
index 4a411bc..bbd06b9 100644 (file)
@@ -187,7 +187,7 @@ except ImportError:
 
         def prf(msg, inner=inner, outer=outer):
             # PBKDF2_HMAC uses the password as key. We can re-use the same
-            # digest objects and and just update copies to skip initialization.
+            # digest objects and just update copies to skip initialization.
             icpy = inner.copy()
             ocpy = outer.copy()
             icpy.update(msg)
index 3dd14a7..1f40d09 100644 (file)
@@ -1,6 +1,6 @@
 """HTML character entity references."""
 
-# maps the HTML entity name to the Unicode codepoint
+# maps the HTML entity name to the Unicode code point
 name2codepoint = {
     'AElig':    0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
     'Aacute':   0x00c1, # latin capital letter A with acute, U+00C1 ISOlat1
@@ -256,7 +256,7 @@ name2codepoint = {
     'zwnj':     0x200c, # zero width non-joiner, U+200C NEW RFC 2070
 }
 
-# maps the Unicode codepoint to the HTML entity name
+# maps the Unicode code point to the HTML entity name
 codepoint2name = {}
 
 # maps the HTML entity name to the character
index ec1dc8c..9f1e088 100644 (file)
@@ -68,6 +68,7 @@ Req-sent-unread-response       _CS_REQ_SENT       <response_class>
 
 from array import array
 import os
+import re
 import socket
 from sys import py3kwarning
 from urlparse import urlsplit
@@ -218,6 +219,38 @@ _MAXLINE = 65536
 # maximum amount of headers accepted
 _MAXHEADERS = 100
 
+# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
+#
+# VCHAR          = %x21-7E
+# obs-text       = %x80-FF
+# header-field   = field-name ":" OWS field-value OWS
+# field-name     = token
+# field-value    = *( field-content / obs-fold )
+# field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+# field-vchar    = VCHAR / obs-text
+#
+# obs-fold       = CRLF 1*( SP / HTAB )
+#                ; obsolete line folding
+#                ; see Section 3.2.4
+
+# token          = 1*tchar
+#
+# tchar          = "!" / "#" / "$" / "%" / "&" / "'" / "*"
+#                / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
+#                / DIGIT / ALPHA
+#                ; any VCHAR, except delimiters
+#
+# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
+
+# the patterns for both name and value are more leniant than RFC
+# definitions to allow for backwards compatibility
+_is_legal_header_name = re.compile(r'\A[^:\s][^:\r\n]*\Z').match
+_is_illegal_header_value = re.compile(r'\n(?![ \t])|\r(?![ \t\n])').search
+
+# We always set the Content-Length header for these methods because some
+# servers will otherwise respond with a 411
+_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
+
 
 class HTTPMessage(mimetools.Message):
 
@@ -313,6 +346,11 @@ class HTTPMessage(mimetools.Message):
                 hlist.append(line)
                 self.addheader(headerseen, line[len(headerseen)+1:].strip())
                 continue
+            elif headerseen is not None:
+                # An empty header name. These aren't allowed in HTTP, but it's
+                # probably a benign mistake. Don't add the header, just keep
+                # going.
+                continue
             else:
                 # It's not a header line; throw it back and stop here.
                 if not self.dict:
@@ -522,9 +560,10 @@ class HTTPResponse:
         return True
 
     def close(self):
-        if self.fp:
-            self.fp.close()
+        fp = self.fp
+        if fp:
             self.fp = None
+            fp.close()
 
     def isclosed(self):
         # NOTE: it is possible that we will not ever call self.close(). This
@@ -723,7 +762,7 @@ class HTTPConnection:
         endpoint passed to set_tunnel. This is done by sending a HTTP CONNECT
         request to the proxy server when the connection is established.
 
-        This method must be called before the HTML connection has been
+        This method must be called before the HTTP connection has been
         established.
 
         The headers argument should be a mapping of extra HTTP headers
@@ -797,13 +836,17 @@ class HTTPConnection:
 
     def close(self):
         """Close the connection to the HTTP server."""
-        if self.sock:
-            self.sock.close()   # close it manually... there may be other refs
-            self.sock = None
-        if self.__response:
-            self.__response.close()
-            self.__response = None
         self.__state = _CS_IDLE
+        try:
+            sock = self.sock
+            if sock:
+                self.sock = None
+                sock.close()   # close it manually... there may be other refs
+        finally:
+            response = self.__response
+            if response:
+                self.__response = None
+                response.close()
 
     def send(self, data):
         """Send `data' to the server."""
@@ -978,7 +1021,16 @@ class HTTPConnection:
         if self.__state != _CS_REQ_STARTED:
             raise CannotSendHeader()
 
-        hdr = '%s: %s' % (header, '\r\n\t'.join([str(v) for v in values]))
+        header = '%s' % header
+        if not _is_legal_header_name(header):
+            raise ValueError('Invalid header name %r' % (header,))
+
+        values = [str(v) for v in values]
+        for one_value in values:
+            if _is_illegal_header_value(one_value):
+                raise ValueError('Invalid header value %r' % (one_value,))
+
+        hdr = '%s: %s' % (header, '\r\n\t'.join(values))
         self._output(hdr)
 
     def endheaders(self, message_body=None):
@@ -1000,19 +1052,25 @@ class HTTPConnection:
         """Send a complete request to the server."""
         self._send_request(method, url, body, headers)
 
-    def _set_content_length(self, body):
-        # Set the content-length based on the body.
+    def _set_content_length(self, body, method):
+        # Set the content-length based on the body. If the body is "empty", we
+        # set Content-Length: 0 for methods that expect a body (RFC 7230,
+        # Section 3.3.2). If the body is set for other methods, we set the
+        # header provided we can figure out what the length is.
         thelen = None
-        try:
-            thelen = str(len(body))
-        except TypeError, te:
-            # If this is a file-like object, try to
-            # fstat its file descriptor
+        if body is None and method.upper() in _METHODS_EXPECTING_BODY:
+            thelen = '0'
+        elif body is not None:
             try:
-                thelen = str(os.fstat(body.fileno()).st_size)
-            except (AttributeError, OSError):
-                # Don't send a length if this failed
-                if self.debuglevel > 0: print "Cannot stat!!"
+                thelen = str(len(body))
+            except TypeError:
+                # If this is a file-like object, try to
+                # fstat its file descriptor
+                try:
+                    thelen = str(os.fstat(body.fileno()).st_size)
+                except (AttributeError, OSError):
+                    # Don't send a length if this failed
+                    if self.debuglevel > 0: print "Cannot stat!!"
 
         if thelen is not None:
             self.putheader('Content-Length', thelen)
@@ -1028,8 +1086,8 @@ class HTTPConnection:
 
         self.putrequest(method, url, **skips)
 
-        if body is not None and 'content-length' not in header_names:
-            self._set_content_length(body)
+        if 'content-length' not in header_names:
+            self._set_content_length(body, method)
         for hdr, value in headers.iteritems():
             self.putheader(hdr, value)
         self.endheaders(body)
@@ -1070,18 +1128,22 @@ class HTTPConnection:
             kwds["buffering"] = True;
         response = self.response_class(*args, **kwds)
 
-        response.begin()
-        assert response.will_close != _UNKNOWN
-        self.__state = _CS_IDLE
+        try:
+            response.begin()
+            assert response.will_close != _UNKNOWN
+            self.__state = _CS_IDLE
 
-        if response.will_close:
-            # this effectively passes the connection to the response
-            self.close()
-        else:
-            # remember this, so we can tell when it is complete
-            self.__response = response
+            if response.will_close:
+                # this effectively passes the connection to the response
+                self.close()
+            else:
+                # remember this, so we can tell when it is complete
+                self.__response = response
 
-        return response
+            return response
+        except:
+            response.close()
+            raise
 
 
 class HTTP:
@@ -1125,7 +1187,7 @@ class HTTP:
         "Accept arguments to set the host/port, since the superclass doesn't."
 
         if host is not None:
-            self._conn._set_hostport(host, port)
+            (self._conn.host, self._conn.port) = self._conn._get_hostport(host, port)
         self._conn.connect()
 
     def getfile(self):
index 2f6f737..bb0cc9c 100644 (file)
@@ -15,8 +15,8 @@ import re
 from sys import maxint as INFINITY
 from idlelib.configHandler import idleConf
 
-BLOCKOPENERS = set(["class", "def", "elif", "else", "except", "finally", "for",
-                    "if", "try", "while", "with"])
+BLOCKOPENERS = {"class", "def", "elif", "else", "except", "finally", "for",
+                    "if", "try", "while", "with"}
 UPDATEINTERVAL = 100 # millisec
 FONTUPDATEINTERVAL = 1000 # millisec
 
index 8ec0f32..d34fc62 100644 (file)
@@ -469,13 +469,10 @@ class EditorWindow(object):
         ("format", "F_ormat"),
         ("run", "_Run"),
         ("options", "_Options"),
-        ("windows", "_Windows"),
+        ("windows", "_Window"),
         ("help", "_Help"),
     ]
 
-    if sys.platform == "darwin":
-        menu_specs[-2] = ("windows", "_Window")
-
 
     def createmenubar(self):
         mbar = self.menubar
index 9b10c0a..7a9d185 100644 (file)
@@ -44,9 +44,11 @@ class FormatParagraph:
 
         The length limit parameter is for testing with a known value.
         """
-        if limit == None:
+        if limit is None:
+            # The default length limit is that defined by pep8
             limit = idleConf.GetOption(
-                    'main', 'FormatParagraph', 'paragraph', type='int')
+                'extensions', 'FormatParagraph', 'max-width',
+                type='int', default=72)
         text = self.editwin.text
         first, last = self.editwin.get_selection_indices()
         if first and last:
index 427d3ce..79db883 100755 (executable)
@@ -871,13 +871,10 @@ class PyShell(OutputWindow):
         ("edit", "_Edit"),
         ("debug", "_Debug"),
         ("options", "_Options"),
-        ("windows", "_Windows"),
+        ("windows", "_Window"),
         ("help", "_Help"),
     ]
 
-    if sys.platform == "darwin":
-        menu_specs[-2] = ("windows", "_Window")
-
 
     # New classes
     from idlelib.IdleHistory import History
@@ -1350,7 +1347,7 @@ class PseudoOutputFile(PseudoFile):
         if type(s) not in (unicode, str, bytearray):
             # See issue #19481
             if isinstance(s, unicode):
-                s = unicode.__getslice__(s, None, None)
+                s = unicode.__getitem__(s, slice(None))
             elif isinstance(s, str):
                 s = str.__str__(s)
             elif isinstance(s, bytearray):
index 2118cd3..963dfd3 100644 (file)
@@ -191,7 +191,7 @@ def search_reverse(prog, chars, col):
 
     This is done by searching forwards until there is no match.
     Prog: compiled re object with a search method returning a match.
-    Chars: line of text, without \n.
+    Chars: line of text, without \\n.
     Col: stop index for the search; the limit for match.end().
     '''
     m = prog.search(chars)
index 5edbd98..a24b8c9 100644 (file)
@@ -66,6 +66,7 @@ toggle-code-context=
 
 [FormatParagraph]
 enable=True
+max-width=72
 [FormatParagraph_cfgBindings]
 format-paragraph=<Alt-Key-q>
 
index 132797c..d7ad59f 100644 (file)
@@ -58,9 +58,6 @@ font-size= 10
 font-bold= 0
 encoding= none
 
-[FormatParagraph]
-paragraph=72
-
 [Indent]
 use-spaces= 1
 num-spaces= 4
index 2187268..c416151 100644 (file)
@@ -371,7 +371,6 @@ class ConfigDialog(Toplevel):
         parent = self.parent
         self.winWidth = StringVar(parent)
         self.winHeight = StringVar(parent)
-        self.paraWidth = StringVar(parent)
         self.startupEdit = IntVar(parent)
         self.autoSave = IntVar(parent)
         self.encoding = StringVar(parent)
@@ -387,7 +386,6 @@ class ConfigDialog(Toplevel):
         frameSave = LabelFrame(frame, borderwidth=2, relief=GROOVE,
                                text=' Autosave Preferences ')
         frameWinSize = Frame(frame, borderwidth=2, relief=GROOVE)
-        frameParaSize = Frame(frame, borderwidth=2, relief=GROOVE)
         frameEncoding = Frame(frame, borderwidth=2, relief=GROOVE)
         frameHelp = LabelFrame(frame, borderwidth=2, relief=GROOVE,
                                text=' Additional Help Sources ')
@@ -416,11 +414,6 @@ class ConfigDialog(Toplevel):
         labelWinHeightTitle = Label(frameWinSize, text='Height')
         entryWinHeight = Entry(
                 frameWinSize, textvariable=self.winHeight, width=3)
-        #paragraphFormatWidth
-        labelParaWidthTitle = Label(
-                frameParaSize, text='Paragraph reformat width (in characters)')
-        entryParaWidth = Entry(
-                frameParaSize, textvariable=self.paraWidth, width=3)
         #frameEncoding
         labelEncodingTitle = Label(
                 frameEncoding, text="Default Source Encoding")
@@ -458,7 +451,6 @@ class ConfigDialog(Toplevel):
         frameRun.pack(side=TOP, padx=5, pady=5, fill=X)
         frameSave.pack(side=TOP, padx=5, pady=5, fill=X)
         frameWinSize.pack(side=TOP, padx=5, pady=5, fill=X)
-        frameParaSize.pack(side=TOP, padx=5, pady=5, fill=X)
         frameEncoding.pack(side=TOP, padx=5, pady=5, fill=X)
         frameHelp.pack(side=TOP, padx=5, pady=5, expand=TRUE, fill=BOTH)
         #frameRun
@@ -475,9 +467,6 @@ class ConfigDialog(Toplevel):
         labelWinHeightTitle.pack(side=RIGHT, anchor=E, pady=5)
         entryWinWidth.pack(side=RIGHT, anchor=E, padx=10, pady=5)
         labelWinWidthTitle.pack(side=RIGHT, anchor=E, pady=5)
-        #paragraphFormatWidth
-        labelParaWidthTitle.pack(side=LEFT, anchor=W, padx=5, pady=5)
-        entryParaWidth.pack(side=RIGHT, anchor=E, padx=10, pady=5)
         #frameEncoding
         labelEncodingTitle.pack(side=LEFT, anchor=W, padx=5, pady=5)
         radioEncNone.pack(side=RIGHT, anchor=E, pady=5)
@@ -509,7 +498,6 @@ class ConfigDialog(Toplevel):
         self.keysAreBuiltin.trace_variable('w', self.VarChanged_keysAreBuiltin)
         self.winWidth.trace_variable('w', self.VarChanged_winWidth)
         self.winHeight.trace_variable('w', self.VarChanged_winHeight)
-        self.paraWidth.trace_variable('w', self.VarChanged_paraWidth)
         self.startupEdit.trace_variable('w', self.VarChanged_startupEdit)
         self.autoSave.trace_variable('w', self.VarChanged_autoSave)
         self.encoding.trace_variable('w', self.VarChanged_encoding)
@@ -594,10 +582,6 @@ class ConfigDialog(Toplevel):
         value = self.winHeight.get()
         self.AddChangedItem('main', 'EditorWindow', 'height', value)
 
-    def VarChanged_paraWidth(self, *params):
-        value = self.paraWidth.get()
-        self.AddChangedItem('main', 'FormatParagraph', 'paragraph', value)
-
     def VarChanged_startupEdit(self, *params):
         value = self.startupEdit.get()
         self.AddChangedItem('main', 'General', 'editor-on-startup', value)
@@ -1094,9 +1078,6 @@ class ConfigDialog(Toplevel):
                 'main', 'EditorWindow', 'width', type='int'))
         self.winHeight.set(idleConf.GetOption(
                 'main', 'EditorWindow', 'height', type='int'))
-        #initial paragraph reformat size
-        self.paraWidth.set(idleConf.GetOption(
-                'main', 'FormatParagraph', 'paragraph', type='int'))
         # default source encoding
         self.encoding.set(idleConf.GetOption(
                 'main', 'EditorWindow', 'encoding', default='none'))
index bd6822c..6b1c002 100644 (file)
@@ -100,7 +100,7 @@ Options Menu:
                          which is scrolling off the top or the window.
                          (Not present in Shell window.)
 
-Windows Menu:
+Window Menu:
 
        Zoom Height -- toggles the window between configured size
        and maximum height.
index e77b96e..3d619a3 100755 (executable)
@@ -1,4 +1,4 @@
-@echo off
-rem Start IDLE using the appropriate Python interpreter
-set CURRDIR=%~dp0
-start "IDLE" "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9
+@echo off\r
+rem Start IDLE using the appropriate Python interpreter\r
+set CURRDIR=%~dp0\r
+start "IDLE" "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9\r
index 58ac28b..147119c 100644 (file)
@@ -55,7 +55,8 @@ class Get_signatureTest(unittest.TestCase):
         def gtest(obj, out):
             self.assertEqual(signature(obj), out)
 
-        gtest(List, '()\n' + List.__doc__)
+        if List.__doc__ is not None:
+            gtest(List, '()\n' + List.__doc__)
         gtest(list.__new__,
                'T.__new__(S, ...) -> a new object with type S, a subtype of T')
         gtest(list.__init__,
@@ -70,7 +71,8 @@ class Get_signatureTest(unittest.TestCase):
 
     def test_signature_wrap(self):
         # This is also a test of an old-style class
-        self.assertEqual(signature(textwrap.TextWrapper), '''\
+        if textwrap.TextWrapper.__doc__ is not None:
+            self.assertEqual(signature(textwrap.TextWrapper), '''\
 (width=70, initial_indent='', subsequent_indent='', expand_tabs=True,
     replace_whitespace=True, fix_sentence_endings=False, break_long_words=True,
     drop_whitespace=True, break_on_hyphens=True)''')
@@ -106,20 +108,23 @@ class Get_signatureTest(unittest.TestCase):
         def t5(a, b=None, *args, **kwds): 'doc'
         t5.tip = "(a, b=None, *args, **kwargs)"
 
+        doc = '\ndoc' if t1.__doc__ is not None else ''
         for func in (t1, t2, t3, t4, t5, TC):
-            self.assertEqual(signature(func), func.tip + '\ndoc')
+            self.assertEqual(signature(func), func.tip + doc)
 
     def test_methods(self):
+        doc = '\ndoc' if TC.__doc__ is not None else ''
         for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__):
-            self.assertEqual(signature(meth), meth.tip + "\ndoc")
-        self.assertEqual(signature(TC.cm), "(a)\ndoc")
-        self.assertEqual(signature(TC.sm), "(b)\ndoc")
+            self.assertEqual(signature(meth), meth.tip + doc)
+        self.assertEqual(signature(TC.cm), "(a)" + doc)
+        self.assertEqual(signature(TC.sm), "(b)" + doc)
 
     def test_bound_methods(self):
         # test that first parameter is correctly removed from argspec
+        doc = '\ndoc' if TC.__doc__ is not None else ''
         for meth, mtip  in ((tc.t1, "()"), (tc.t4, "(*args)"), (tc.t6, "(self)"),
                             (tc.__call__, '(ci)'), (tc, '(ci)'), (TC.cm, "(a)"),):
-            self.assertEqual(signature(meth), mtip + "\ndoc")
+            self.assertEqual(signature(meth), mtip + doc)
 
     def test_starred_parameter(self):
         # test that starred first parameter is *not* removed from argspec
diff --git a/Lib/idlelib/idle_test/test_io.py b/Lib/idlelib/idle_test/test_io.py
new file mode 100644 (file)
index 0000000..ee017bb
--- /dev/null
@@ -0,0 +1,267 @@
+import unittest
+import io
+from idlelib.PyShell import PseudoInputFile, PseudoOutputFile
+from test import test_support as support
+
+
+class Base(object):
+    def __str__(self):
+        return '%s:str' % type(self).__name__
+    def __unicode__(self):
+        return '%s:unicode' % type(self).__name__
+    def __len__(self):
+        return 3
+    def __iter__(self):
+        return iter('abc')
+    def __getitem__(self, *args):
+        return '%s:item' % type(self).__name__
+    def __getslice__(self, *args):
+        return '%s:slice' % type(self).__name__
+
+class S(Base, str):
+    pass
+
+class U(Base, unicode):
+    pass
+
+class BA(Base, bytearray):
+    pass
+
+class MockShell:
+    def __init__(self):
+        self.reset()
+
+    def write(self, *args):
+        self.written.append(args)
+
+    def readline(self):
+        return self.lines.pop()
+
+    def close(self):
+        pass
+
+    def reset(self):
+        self.written = []
+
+    def push(self, lines):
+        self.lines = list(lines)[::-1]
+
+
+class PseudeOutputFilesTest(unittest.TestCase):
+    def test_misc(self):
+        shell = MockShell()
+        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
+        self.assertIsInstance(f, io.TextIOBase)
+        self.assertEqual(f.encoding, 'utf-8')
+        self.assertIsNone(f.errors)
+        self.assertIsNone(f.newlines)
+        self.assertEqual(f.name, '<stdout>')
+        self.assertFalse(f.closed)
+        self.assertTrue(f.isatty())
+        self.assertFalse(f.readable())
+        self.assertTrue(f.writable())
+        self.assertFalse(f.seekable())
+
+    def test_unsupported(self):
+        shell = MockShell()
+        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
+        self.assertRaises(IOError, f.fileno)
+        self.assertRaises(IOError, f.tell)
+        self.assertRaises(IOError, f.seek, 0)
+        self.assertRaises(IOError, f.read, 0)
+        self.assertRaises(IOError, f.readline, 0)
+
+    def test_write(self):
+        shell = MockShell()
+        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
+        f.write('test')
+        self.assertEqual(shell.written, [('test', 'stdout')])
+        shell.reset()
+        f.write('t\xe8st')
+        self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
+        shell.reset()
+        f.write(u't\xe8st')
+        self.assertEqual(shell.written, [(u't\xe8st', 'stdout')])
+        shell.reset()
+
+        f.write(S('t\xe8st'))
+        self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), str)
+        shell.reset()
+        f.write(BA('t\xe8st'))
+        self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), str)
+        shell.reset()
+        f.write(U(u't\xe8st'))
+        self.assertEqual(shell.written, [(u't\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), unicode)
+        shell.reset()
+
+        self.assertRaises(TypeError, f.write)
+        self.assertEqual(shell.written, [])
+        self.assertRaises(TypeError, f.write, 123)
+        self.assertEqual(shell.written, [])
+        self.assertRaises(TypeError, f.write, 'test', 'spam')
+        self.assertEqual(shell.written, [])
+
+    def test_writelines(self):
+        shell = MockShell()
+        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
+        f.writelines([])
+        self.assertEqual(shell.written, [])
+        shell.reset()
+        f.writelines(['one\n', 'two'])
+        self.assertEqual(shell.written,
+                         [('one\n', 'stdout'), ('two', 'stdout')])
+        shell.reset()
+        f.writelines(['on\xe8\n', 'tw\xf2'])
+        self.assertEqual(shell.written,
+                         [('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')])
+        shell.reset()
+        f.writelines([u'on\xe8\n', u'tw\xf2'])
+        self.assertEqual(shell.written,
+                         [(u'on\xe8\n', 'stdout'), (u'tw\xf2', 'stdout')])
+        shell.reset()
+
+        f.writelines([S('t\xe8st')])
+        self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), str)
+        shell.reset()
+        f.writelines([BA('t\xe8st')])
+        self.assertEqual(shell.written, [('t\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), str)
+        shell.reset()
+        f.writelines([U(u't\xe8st')])
+        self.assertEqual(shell.written, [(u't\xe8st', 'stdout')])
+        self.assertEqual(type(shell.written[0][0]), unicode)
+        shell.reset()
+
+        self.assertRaises(TypeError, f.writelines)
+        self.assertEqual(shell.written, [])
+        self.assertRaises(TypeError, f.writelines, 123)
+        self.assertEqual(shell.written, [])
+        self.assertRaises(TypeError, f.writelines, [123])
+        self.assertEqual(shell.written, [])
+        self.assertRaises(TypeError, f.writelines, [], [])
+        self.assertEqual(shell.written, [])
+
+    def test_close(self):
+        shell = MockShell()
+        f = PseudoOutputFile(shell, 'stdout', 'utf-8')
+        self.assertFalse(f.closed)
+        f.write('test')
+        f.close()
+        self.assertTrue(f.closed)
+        self.assertRaises(ValueError, f.write, 'x')
+        self.assertEqual(shell.written, [('test', 'stdout')])
+        f.close()
+        self.assertRaises(TypeError, f.close, 1)
+
+
+class PseudeInputFilesTest(unittest.TestCase):
+    def test_misc(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        self.assertIsInstance(f, io.TextIOBase)
+        self.assertEqual(f.encoding, 'utf-8')
+        self.assertIsNone(f.errors)
+        self.assertIsNone(f.newlines)
+        self.assertEqual(f.name, '<stdin>')
+        self.assertFalse(f.closed)
+        self.assertTrue(f.isatty())
+        self.assertTrue(f.readable())
+        self.assertFalse(f.writable())
+        self.assertFalse(f.seekable())
+
+    def test_unsupported(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        self.assertRaises(IOError, f.fileno)
+        self.assertRaises(IOError, f.tell)
+        self.assertRaises(IOError, f.seek, 0)
+        self.assertRaises(IOError, f.write, 'x')
+        self.assertRaises(IOError, f.writelines, ['x'])
+
+    def test_read(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.read(), 'one\ntwo\n')
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.read(-1), 'one\ntwo\n')
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.read(None), 'one\ntwo\n')
+        shell.push(['one\n', 'two\n', 'three\n', ''])
+        self.assertEqual(f.read(2), 'on')
+        self.assertEqual(f.read(3), 'e\nt')
+        self.assertEqual(f.read(10), 'wo\nthree\n')
+
+        shell.push(['one\n', 'two\n'])
+        self.assertEqual(f.read(0), '')
+        self.assertRaises(TypeError, f.read, 1.5)
+        self.assertRaises(TypeError, f.read, '1')
+        self.assertRaises(TypeError, f.read, 1, 1)
+
+    def test_readline(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        shell.push(['one\n', 'two\n', 'three\n', 'four\n'])
+        self.assertEqual(f.readline(), 'one\n')
+        self.assertEqual(f.readline(-1), 'two\n')
+        self.assertEqual(f.readline(None), 'three\n')
+        shell.push(['one\ntwo\n'])
+        self.assertEqual(f.readline(), 'one\n')
+        self.assertEqual(f.readline(), 'two\n')
+        shell.push(['one', 'two', 'three'])
+        self.assertEqual(f.readline(), 'one')
+        self.assertEqual(f.readline(), 'two')
+        shell.push(['one\n', 'two\n', 'three\n'])
+        self.assertEqual(f.readline(2), 'on')
+        self.assertEqual(f.readline(1), 'e')
+        self.assertEqual(f.readline(1), '\n')
+        self.assertEqual(f.readline(10), 'two\n')
+
+        shell.push(['one\n', 'two\n'])
+        self.assertEqual(f.readline(0), '')
+        self.assertRaises(TypeError, f.readlines, 1.5)
+        self.assertRaises(TypeError, f.readlines, '1')
+        self.assertRaises(TypeError, f.readlines, 1, 1)
+
+    def test_readlines(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(), ['one\n', 'two\n'])
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(-1), ['one\n', 'two\n'])
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(None), ['one\n', 'two\n'])
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(0), ['one\n', 'two\n'])
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(3), ['one\n'])
+        shell.push(['one\n', 'two\n', ''])
+        self.assertEqual(f.readlines(4), ['one\n', 'two\n'])
+
+        shell.push(['one\n', 'two\n', ''])
+        self.assertRaises(TypeError, f.readlines, 1.5)
+        self.assertRaises(TypeError, f.readlines, '1')
+        self.assertRaises(TypeError, f.readlines, 1, 1)
+
+    def test_close(self):
+        shell = MockShell()
+        f = PseudoInputFile(shell, 'stdin', 'utf-8')
+        shell.push(['one\n', 'two\n', ''])
+        self.assertFalse(f.closed)
+        self.assertEqual(f.readline(), 'one\n')
+        f.close()
+        self.assertFalse(f.closed)
+        self.assertEqual(f.readline(), 'two\n')
+        self.assertRaises(TypeError, f.close, 1)
+
+
+def test_main():
+    support.run_unittest(PseudeOutputFilesTest, PseudeInputFilesTest)
+
+if __name__ == '__main__':
+    test_main()
index ba1b4d5..563d933 100644 (file)
@@ -1 +1,4 @@
-IDLE_VERSION = "2.7.9"
+"""Unused by Idle: there is no separate Idle version anymore.
+Kept only for possible existing extension use."""
+from sys import version
+IDLE_VERSION = version[:version.index(' ')]
diff --git a/Lib/idlelib/testcode.py b/Lib/idlelib/testcode.py
deleted file mode 100644 (file)
index 05eaa56..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-import string
-
-def f():
-    a = 0
-    b = 1
-    c = 2
-    d = 3
-    e = 4
-    g()
-
-def g():
-    h()
-
-def h():
-    i()
-
-def i():
-    j()
-
-def j():
-    k()
-
-def k():
-    l()
-
-l = lambda: test()
-
-def test():
-    string.capwords(1)
-
-f()
index 10ff340..826eea2 100644 (file)
@@ -37,11 +37,12 @@ AllowedVersions = ('IMAP4REV1', 'IMAP4')        # Most recent first
 
 # Maximal line length when calling readline(). This is to prevent
 # reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1)
-# don't specify a line length. RFC 2683 however suggests limiting client
-# command lines to 1000 octets and server command lines to 8000 octets.
-# We have selected 10000 for some extra margin and since that is supposedly
-# also what UW and Panda IMAP does.
-_MAXLINE = 10000
+# don't specify a line length. RFC 2683 suggests limiting client
+# command lines to 1000 octets and that servers should be prepared
+# to accept command lines up to 8000 octets, so we used to use 10K here.
+# In the modern world (eg: gmail) the response to, for example, a
+# search command can be quite large, so we now use 1M.
+_MAXLINE = 1000000
 
 
 #       Commands
index 8d21717..cb7edf0 100644 (file)
@@ -401,6 +401,10 @@ class BooleanVar(Variable):
         """
         Variable.__init__(self, master, value, name)
 
+    def set(self, value):
+        """Set the variable to VALUE."""
+        return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
+
     def get(self):
         """Return the value of the variable as a bool."""
         return self._tk.getboolean(self._tk.globalgetvar(self._name))
index c11d8cd..5e07528 100644 (file)
@@ -1,6 +1,7 @@
 import unittest
 
-from Tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl, TclError
+from Tkinter import (Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl,
+                     TclError)
 
 
 class TestBase(unittest.TestCase):
@@ -139,16 +140,57 @@ class TestBooleanVar(TestBase):
 
     def test_default(self):
         v = BooleanVar(self.root)
-        self.assertEqual(False, v.get())
+        self.assertIs(v.get(), False)
 
     def test_get(self):
         v = BooleanVar(self.root, True, "name")
-        self.assertAlmostEqual(True, v.get())
+        self.assertIs(v.get(), True)
         self.root.globalsetvar("name", "0")
-        self.assertAlmostEqual(False, v.get())
+        self.assertIs(v.get(), False)
+        self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1)
+        self.assertIs(v.get(), True)
+        self.root.globalsetvar("name", 0)
+        self.assertIs(v.get(), False)
+        self.root.globalsetvar("name", 42L if self.root.wantobjects() else 1L)
+        self.assertIs(v.get(), True)
+        self.root.globalsetvar("name", 0L)
+        self.assertIs(v.get(), False)
+        self.root.globalsetvar("name", "on")
+        self.assertIs(v.get(), True)
+        self.root.globalsetvar("name", u"0")
+        self.assertIs(v.get(), False)
+        self.root.globalsetvar("name", u"on")
+        self.assertIs(v.get(), True)
+
+    def test_set(self):
+        true = 1 if self.root.wantobjects() else "1"
+        false = 0 if self.root.wantobjects() else "0"
+        v = BooleanVar(self.root, name="name")
+        v.set(True)
+        self.assertEqual(self.root.globalgetvar("name"), true)
+        v.set("0")
+        self.assertEqual(self.root.globalgetvar("name"), false)
+        v.set(42)
+        self.assertEqual(self.root.globalgetvar("name"), true)
+        v.set(0)
+        self.assertEqual(self.root.globalgetvar("name"), false)
+        v.set(42L)
+        self.assertEqual(self.root.globalgetvar("name"), true)
+        v.set(0L)
+        self.assertEqual(self.root.globalgetvar("name"), false)
+        v.set("on")
+        self.assertEqual(self.root.globalgetvar("name"), true)
+        v.set(u"0")
+        self.assertEqual(self.root.globalgetvar("name"), false)
+        v.set(u"on")
+        self.assertEqual(self.root.globalgetvar("name"), true)
 
     def test_invalid_value_domain(self):
+        false = 0 if self.root.wantobjects() else "0"
         v = BooleanVar(self.root, name="name")
+        with self.assertRaises(TclError):
+            v.set("value")
+        self.assertEqual(self.root.globalgetvar("name"), false)
         self.root.globalsetvar("name", "value")
         with self.assertRaises(TclError):
             v.get()
index efb9a05..1916e34 100644 (file)
@@ -1037,7 +1037,7 @@ class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
     def test_paneconfigure_height(self):
         p, b, c = self.create2()
         self.check_paneconfigure(p, b, 'height', 10, 10,
-                                 stringify=tcl_version < (8, 5))
+                                 stringify=get_tk_patchlevel() < (8, 5, 11))
         self.check_paneconfigure_bad(p, b, 'height',
                                      'bad screen distance "badValue"')
 
@@ -1085,7 +1085,7 @@ class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
     def test_paneconfigure_width(self):
         p, b, c = self.create2()
         self.check_paneconfigure(p, b, 'width', 10, 10,
-                                 stringify=tcl_version < (8, 5))
+                                 stringify=get_tk_patchlevel() < (8, 5, 11))
         self.check_paneconfigure_bad(p, b, 'width',
                                      'bad screen distance "badValue"')
 
index c335f29..91795d9 100644 (file)
@@ -1,3 +1,4 @@
+import re
 import unittest
 import Tkinter as tkinter
 
@@ -61,14 +62,15 @@ def get_tk_patchlevel():
     global _tk_patchlevel
     if _tk_patchlevel is None:
         tcl = tkinter.Tcl()
-        patchlevel = []
-        for x in tcl.call('info', 'patchlevel').split('.'):
-            try:
-                x = int(x, 10)
-            except ValueError:
-                x = -1
-            patchlevel.append(x)
-        _tk_patchlevel = tuple(patchlevel)
+        patchlevel = tcl.call('info', 'patchlevel')
+        m = re.match(r'(\d+)\.(\d+)([ab.])(\d+)$', patchlevel)
+        major, minor, releaselevel, serial = m.groups()
+        major, minor, serial = int(major), int(minor), int(serial)
+        releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
+        if releaselevel == 'final':
+            _tk_patchlevel = major, minor, serial, releaselevel, 0
+        else:
+            _tk_patchlevel = major, minor, 0, releaselevel, serial
     return _tk_patchlevel
 
 units = {
index 6848905..71de83f 100644 (file)
@@ -22,7 +22,7 @@ class StandardTtkOptionsTests(StandardOptionsTests):
         widget = self.create()
         self.assertEqual(widget['class'], '')
         errmsg='attempt to change read-only option'
-        if get_tk_patchlevel() < (8, 6, 0): # actually this was changed in 8.6b3
+        if get_tk_patchlevel() < (8, 6, 0, 'beta', 3):
             errmsg='Attempt to change read-only option'
         self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg)
         widget2 = self.create(class_='Foo')
@@ -553,7 +553,7 @@ class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
         widget = self.create()
         self.assertEqual(str(widget['orient']), 'vertical')
         errmsg='attempt to change read-only option'
-        if get_tk_patchlevel() < (8, 6, 0): # actually this was changed in 8.6b3
+        if get_tk_patchlevel() < (8, 6, 0, 'beta', 3):
             errmsg='Attempt to change read-only option'
         self.checkInvalidParam(widget, 'orient', 'horizontal',
                 errmsg=errmsg)
index 58f7698..08cb040 100644 (file)
@@ -575,7 +575,7 @@ class Widget(Tkinter.Widget):
         if ret and callback:
             return callback(*args, **kw)
 
-        return bool(ret)
+        return ret
 
 
     def state(self, statespec=None):
@@ -683,7 +683,7 @@ class Entry(Widget, Tkinter.Entry):
         """Force revalidation, independent of the conditions specified
         by the validate option. Returns False if validation fails, True
         if it succeeds. Sets or clears the invalid state accordingly."""
-        return bool(self.tk.getboolean(self.tk.call(self._w, "validate")))
+        return self.tk.getboolean(self.tk.call(self._w, "validate"))
 
 
 class Combobox(Entry):
@@ -1233,7 +1233,7 @@ class Treeview(Widget, Tkinter.XView, Tkinter.YView):
     def exists(self, item):
         """Returns True if the specified item is present in the tree,
         False otherwise."""
-        return bool(self.tk.getboolean(self.tk.call(self._w, "exists", item)))
+        return self.tk.getboolean(self.tk.call(self._w, "exists", item))
 
 
     def focus(self, item=None):
index 75673a4..73a7590 100644 (file)
@@ -1235,7 +1235,7 @@ class TurtleScreen(TurtleScreenBase):
     def _incrementudc(self):
         """Increment update counter."""
         if not TurtleScreen._RUNNING:
-            TurtleScreen._RUNNNING = True
+            TurtleScreen._RUNNING = True
             raise Terminator
         if self._tracing > 0:
             self._updatecounter += 1
@@ -3644,7 +3644,7 @@ class _Screen(TurtleScreen):
             Turtle._screen = None
             _Screen._root = None
             _Screen._canvas = None
-        TurtleScreen._RUNNING = True
+        TurtleScreen._RUNNING = False
         root.destroy()
 
     def bye(self):
@@ -3685,7 +3685,6 @@ class _Screen(TurtleScreen):
         except AttributeError:
             exit(0)
 
-
 class Turtle(RawTurtle):
     """RawTurtle auto-creating (scrolled) canvas.
 
@@ -3708,18 +3707,6 @@ class Turtle(RawTurtle):
 
 Pen = Turtle
 
-def _getpen():
-    """Create the 'anonymous' turtle if not already present."""
-    if Turtle._pen is None:
-        Turtle._pen = Turtle()
-    return Turtle._pen
-
-def _getscreen():
-    """Create a TurtleScreen if not already present."""
-    if Turtle._screen is None:
-        Turtle._screen = Screen()
-    return Turtle._screen
-
 def write_docstringdict(filename="turtle_docstringdict"):
     """Create and write docstring-dictionary to file.
 
@@ -3847,30 +3834,41 @@ def _screen_docrevise(docstr):
 ## as functions. So we can enhance, change, add, delete methods to these
 ## classes and do not need to change anything here.
 
+__func_body = """\
+def {name}{paramslist}:
+    if {obj} is None:
+        if not TurtleScreen._RUNNING:
+            TurtleScreen._RUNNING = True
+            raise Terminator
+        {obj} = {init}
+    try:
+        return {obj}.{name}{argslist}
+    except TK.TclError:
+        if not TurtleScreen._RUNNING:
+            TurtleScreen._RUNNING = True
+            raise Terminator
+        raise
+"""
 
-for methodname in _tg_screen_functions:
-    pl1, pl2 = getmethparlist(eval('_Screen.' + methodname))
-    if pl1 == "":
-        print ">>>>>>", pl1, pl2
-        continue
-    defstr = ("def %(key)s%(pl1)s: return _getscreen().%(key)s%(pl2)s" %
-                                   {'key':methodname, 'pl1':pl1, 'pl2':pl2})
-    exec defstr
-    eval(methodname).__doc__ = _screen_docrevise(eval('_Screen.'+methodname).__doc__)
+def _make_global_funcs(functions, cls, obj, init, docrevise):
+    for methodname in functions:
+        method = getattr(cls, methodname)
+        pl1, pl2 = getmethparlist(method)
+        if pl1 == "":
+            print ">>>>>>", pl1, pl2
+            continue
+        defstr = __func_body.format(obj=obj, init=init, name=methodname,
+                                    paramslist=pl1, argslist=pl2)
+        exec defstr in globals()
+        globals()[methodname].__doc__ = docrevise(method.__doc__)
 
-for methodname in _tg_turtle_functions:
-    pl1, pl2 = getmethparlist(eval('Turtle.' + methodname))
-    if pl1 == "":
-        print ">>>>>>", pl1, pl2
-        continue
-    defstr = ("def %(key)s%(pl1)s: return _getpen().%(key)s%(pl2)s" %
-                                   {'key':methodname, 'pl1':pl1, 'pl2':pl2})
-    exec defstr
-    eval(methodname).__doc__ = _turtle_docrevise(eval('Turtle.'+methodname).__doc__)
+_make_global_funcs(_tg_screen_functions, _Screen,
+                   'Turtle._screen', 'Screen()', _screen_docrevise)
+_make_global_funcs(_tg_turtle_functions, Turtle,
+                   'Turtle._pen', 'Turtle()', _turtle_docrevise)
 
 
 done = mainloop = TK.mainloop
-del pl1, pl2, defstr
 
 if __name__ == "__main__":
     def switchpen():
index 89fb3db..3f3fbbf 100644 (file)
@@ -35,7 +35,7 @@ class FixExitfunc(fixer_base.BaseFix):
         self.sys_import = None
 
     def transform(self, node, results):
-        # First, find the sys import. We'll just hope it's global scope.
+        # First, find the sys import. We'll just hope it's global scope.
         if "sys_import" in results:
             if self.sys_import is None:
                 self.sys_import = results["sys_import"]
index 811f27f..4b97be3 100644 (file)
@@ -36,8 +36,12 @@ def getlines(filename, module_globals=None):
 
     if filename in cache:
         return cache[filename][2]
-    else:
+
+    try:
         return updatecache(filename, module_globals)
+    except MemoryError:
+        clearcache()
+        return []
 
 
 def checkcache(filename=None):
index b2a7711..bd4afeb 100644 (file)
@@ -916,14 +916,19 @@ class FileHandler(StreamHandler):
         """
         self.acquire()
         try:
-            if self.stream:
-                self.flush()
-                if hasattr(self.stream, "close"):
-                    self.stream.close()
-                self.stream = None
-            # Issue #19523: call unconditionally to
-            # prevent a handler leak when delay is set
-            StreamHandler.close(self)
+            try:
+                if self.stream:
+                    try:
+                        self.flush()
+                    finally:
+                        stream = self.stream
+                        self.stream = None
+                        if hasattr(stream, "close"):
+                            stream.close()
+            finally:
+                # Issue #19523: call unconditionally to
+                # prevent a handler leak when delay is set
+                StreamHandler.close(self)
         finally:
             self.release()
 
index a458529..e430ab7 100644 (file)
@@ -588,9 +588,10 @@ class SocketHandler(logging.Handler):
         """
         self.acquire()
         try:
-            if self.sock:
-                self.sock.close()
+            sock = self.sock
+            if sock:
                 self.sock = None
+                sock.close()
         finally:
             self.release()
         logging.Handler.close(self)
@@ -1160,8 +1161,10 @@ class BufferingHandler(logging.Handler):
 
         This version just flushes and chains to the parent class' close().
         """
-        self.flush()
-        logging.Handler.close(self)
+        try:
+            self.flush()
+        finally:
+            logging.Handler.close(self)
 
 class MemoryHandler(BufferingHandler):
     """
@@ -1213,10 +1216,12 @@ class MemoryHandler(BufferingHandler):
         """
         Flush, set the target to None and lose the buffer.
         """
-        self.flush()
-        self.acquire()
         try:
-            self.target = None
-            BufferingHandler.close(self)
+            self.flush()
         finally:
-            self.release()
+            self.acquire()
+            try:
+                self.target = None
+                BufferingHandler.close(self)
+            finally:
+                self.release()
index c31bdaa..9ebd83c 100644 (file)
@@ -5,6 +5,7 @@ import warnings
 from stat import *
 import genericpath
 from genericpath import *
+from genericpath import _unicode
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
            "basename","dirname","commonprefix","getsize","getmtime",
@@ -186,7 +187,7 @@ def walk(top, func, arg):
 def abspath(path):
     """Return an absolute path."""
     if not isabs(path):
-        if isinstance(path, unicode):
+        if isinstance(path, _unicode):
             cwd = os.getcwdu()
         else:
             cwd = os.getcwd()
index ba49753..3866953 100644 (file)
@@ -719,10 +719,14 @@ class _singlefileMailbox(Mailbox):
 
     def close(self):
         """Flush and close the mailbox."""
-        self.flush()
-        if self._locked:
-            self.unlock()
-        self._file.close()  # Sync has been done by self.flush() above.
+        try:
+            self.flush()
+        finally:
+            try:
+                if self._locked:
+                    self.unlock()
+            finally:
+                self._file.close()  # Sync has been done by self.flush() above.
 
     def _lookup(self, key=None):
         """Return (start, stop) or raise KeyError."""
index ec8fd99..a39b543 100644 (file)
@@ -242,9 +242,12 @@ class MimeTypes:
             i = 0
             while True:
                 try:
-                    yield _winreg.EnumKey(mimedb, i)
+                    ctype = _winreg.EnumKey(mimedb, i)
                 except EnvironmentError:
                     break
+                else:
+                    if '\0' not in ctype:
+                        yield ctype
                 i += 1
 
         default_encoding = sys.getdefaultencoding()
index f6f84f3..f16b2c7 100644 (file)
@@ -109,16 +109,16 @@ class ModuleFinder:
 
     def run_script(self, pathname):
         self.msg(2, "run_script", pathname)
-        fp = open(pathname, READ_MODE)
-        stuff = ("", "r", imp.PY_SOURCE)
-        self.load_module('__main__', fp, pathname, stuff)
+        with open(pathname, READ_MODE) as fp:
+            stuff = ("", "r", imp.PY_SOURCE)
+            self.load_module('__main__', fp, pathname, stuff)
 
     def load_file(self, pathname):
         dir, name = os.path.split(pathname)
         name, ext = os.path.splitext(name)
-        fp = open(pathname, READ_MODE)
-        stuff = (ext, "r", imp.PY_SOURCE)
-        self.load_module(name, fp, pathname, stuff)
+        with open(pathname, READ_MODE) as fp:
+            stuff = (ext, "r", imp.PY_SOURCE)
+            self.load_module(name, fp, pathname, stuff)
 
     def import_hook(self, name, caller=None, fromlist=None, level=-1):
         self.msg(3, "import_hook", name, caller, fromlist, level)
@@ -461,6 +461,8 @@ class ModuleFinder:
         fp, buf, stuff = self.find_module("__init__", m.__path__)
         self.load_module(fqname, fp, buf, stuff)
         self.msgout(2, "load_package ->", m)
+        if fp:
+            fp.close()
         return m
 
     def add_module(self, fqname):
index e4d520f..645a26f 100644 (file)
@@ -285,9 +285,13 @@ class SocketListener(object):
         return conn
 
     def close(self):
-        self._socket.close()
-        if self._unlink is not None:
-            self._unlink()
+        try:
+            self._socket.close()
+        finally:
+            unlink = self._unlink
+            if unlink is not None:
+                self._unlink = None
+                unlink()
 
 
 def SocketClient(address):
@@ -454,10 +458,10 @@ class ConnectionWrapper(object):
         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)
 
 def _xml_loads(s):
-    (obj,), method = xmlrpclib.loads(s.decode('utf8'))
+    (obj,), method = xmlrpclib.loads(s)
     return obj
 
 class XmlListener(Listener):
index 04531b9..991f87f 100644 (file)
@@ -334,25 +334,34 @@ class Pool(object):
         thread = threading.current_thread()
 
         for taskseq, set_length in iter(taskqueue.get, None):
+            task = None
             i = -1
-            for i, task in enumerate(taskseq):
-                if thread._state:
-                    debug('task handler found thread._state != RUN')
-                    break
-                try:
-                    put(task)
-                except Exception as e:
-                    job, ind = task[:2]
+            try:
+                for i, task in enumerate(taskseq):
+                    if thread._state:
+                        debug('task handler found thread._state != RUN')
+                        break
                     try:
-                        cache[job]._set(ind, (False, e))
-                    except KeyError:
-                        pass
-            else:
+                        put(task)
+                    except Exception as e:
+                        job, ind = task[:2]
+                        try:
+                            cache[job]._set(ind, (False, e))
+                        except KeyError:
+                            pass
+                else:
+                    if set_length:
+                        debug('doing set_length()')
+                        set_length(i+1)
+                    continue
+                break
+            except Exception as ex:
+                job, ind = task[:2] if task else (0, 0)
+                if job in cache:
+                    cache[job]._set(ind + 1, (False, ex))
                 if set_length:
                     debug('doing set_length()')
                     set_length(i+1)
-                continue
-            break
         else:
             debug('task handler got sentinel')
 
index 433c7e2..a88e298 100644 (file)
@@ -44,10 +44,10 @@ import weakref
 
 from Queue import Empty, Full
 import _multiprocessing
-from multiprocessing import Pipe
-from multiprocessing.synchronize import Lock, BoundedSemaphore, Semaphore, Condition
-from multiprocessing.util import debug, info, Finalize, register_after_fork
-from multiprocessing.forking import assert_spawning
+from . import Pipe
+from .synchronize import Lock, BoundedSemaphore, Semaphore, Condition
+from .util import debug, info, Finalize, register_after_fork, is_exiting
+from .forking import assert_spawning
 
 #
 # Queue type using a pipe, buffer and thread
@@ -156,9 +156,13 @@ class Queue(object):
 
     def close(self):
         self._closed = True
-        self._reader.close()
-        if self._close:
-            self._close()
+        try:
+            self._reader.close()
+        finally:
+            close = self._close
+            if close:
+                self._close = None
+                close()
 
     def join_thread(self):
         debug('Queue.join_thread()')
@@ -229,8 +233,6 @@ class Queue(object):
     @staticmethod
     def _feed(buffer, notempty, send, writelock, close):
         debug('starting thread to feed data to pipe')
-        from .util import is_exiting
-
         nacquire = notempty.acquire
         nrelease = notempty.release
         nwait = notempty.wait
index 1eb044d..58415fc 100644 (file)
@@ -46,13 +46,18 @@ __all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']
 #
 
 typecode_to_type = {
-    'c': ctypes.c_char,  'u': ctypes.c_wchar,
+    'c': ctypes.c_char,
     'b': ctypes.c_byte,  'B': ctypes.c_ubyte,
     'h': ctypes.c_short, 'H': ctypes.c_ushort,
     'i': ctypes.c_int,   'I': ctypes.c_uint,
     'l': ctypes.c_long,  'L': ctypes.c_ulong,
     'f': ctypes.c_float, 'd': ctypes.c_double
     }
+try:
+    typecode_to_type['u'] = ctypes.c_wchar
+except AttributeError:
+    pass
+
 
 #
 #
index fcaf21b..58951b9 100644 (file)
@@ -12,6 +12,7 @@ import genericpath
 import warnings
 
 from genericpath import *
+from genericpath import _unicode
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
            "basename","dirname","commonprefix","getsize","getmtime",
@@ -331,7 +332,7 @@ def expandvars(path):
         return path
     import string
     varchars = string.ascii_letters + string.digits + '_-'
-    if isinstance(path, unicode):
+    if isinstance(path, _unicode):
         encoding = sys.getfilesystemencoding()
         def getenv(var):
             return os.environ[var.encode(encoding)].decode(encoding)
@@ -350,7 +351,7 @@ def expandvars(path):
                 index = path.index('\'')
                 res = res + '\'' + path[:index + 1]
             except ValueError:
-                res = res + path
+                res = res + c + path
                 index = pathlen - 1
         elif c == '%':  # variable or '%'
             if path[index + 1:index + 2] == '%':
@@ -414,7 +415,7 @@ def expandvars(path):
 def normpath(path):
     """Normalize path, eliminating double slashes, etc."""
     # Preserve unicode (if path is unicode)
-    backslash, dot = (u'\\', u'.') if isinstance(path, unicode) else ('\\', '.')
+    backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.')
     if path.startswith(('\\\\.\\', '\\\\?\\')):
         # in the case of paths with these prefixes:
         # \\.\ -> device names
@@ -471,7 +472,7 @@ except ImportError: # not running on Windows - mock up something sensible
     def abspath(path):
         """Return the absolute version of a path."""
         if not isabs(path):
-            if isinstance(path, unicode):
+            if isinstance(path, _unicode):
                 cwd = os.getcwdu()
             else:
                 cwd = os.getcwd()
@@ -487,7 +488,7 @@ else:  # use native Windows method on Windows
                 path = _getfullpathname(path)
             except WindowsError:
                 pass # Bad path - return unchanged.
-        elif isinstance(path, unicode):
+        elif isinstance(path, _unicode):
             path = os.getcwdu()
         else:
             path = os.getcwd()
index 53fad6b..cfea71b 100644 (file)
--- a/Lib/os.py
+++ b/Lib/os.py
@@ -185,7 +185,7 @@ def renames(old, new):
     empty.  Works like rename, except creation of any intermediate
     directories needed to make the new pathname good is attempted
     first.  After the rename, directories corresponding to rightmost
-    path segments of the old name will be pruned way until either the
+    path segments of the old name will be pruned until either the
     whole path is consumed or a nonempty directory is found.
 
     Note: this function can fail with the new directory structure made
index 1bed51d..0b32d63 100644 (file)
@@ -8,6 +8,7 @@ module as os.path.
 import os
 import stat
 from genericpath import *
+from genericpath import _unicode
 from ntpath import (expanduser, expandvars, isabs, islink, splitdrive,
                     splitext, split, walk)
 
@@ -146,7 +147,7 @@ def normpath(path):
 def abspath(path):
     """Return the absolute version of a path"""
     if not isabs(path):
-        if isinstance(path, unicode):
+        if isinstance(path, _unicode):
             cwd = os.getcwdu()
         else:
             cwd = os.getcwd()
index 0378004..6578481 100644 (file)
@@ -16,14 +16,7 @@ import stat
 import genericpath
 import warnings
 from genericpath import *
-
-try:
-    _unicode = unicode
-except NameError:
-    # If Python is built without Unicode support, the unicode type
-    # will not exist. Fake one.
-    class _unicode(object):
-        pass
+from genericpath import _unicode
 
 __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
            "basename","dirname","commonprefix","getsize","getmtime",
@@ -294,16 +287,16 @@ def expandvars(path):
     if '$' not in path:
         return path
     if isinstance(path, _unicode):
-        if not _varprog:
+        if not _uvarprog:
             import re
-            _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
-        varprog = _varprog
+            _uvarprog = re.compile(ur'\$(\w+|\{[^}]*\})', re.UNICODE)
+        varprog = _uvarprog
         encoding = sys.getfilesystemencoding()
     else:
-        if not _uvarprog:
+        if not _varprog:
             import re
-            _uvarprog = re.compile(_unicode(r'\$(\w+|\{[^}]*\})'), re.UNICODE)
-        varprog = _uvarprog
+            _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
+        varprog = _varprog
         encoding = None
     i = 0
     while True:
index c0bc1e4..8334ed9 100644 (file)
@@ -163,7 +163,7 @@ def main(args=None):
             except PyCompileError as error:
                 # return value to indicate at least one failure
                 rv = 1
-                sys.stderr.write(error.msg)
+                sys.stderr.write("%s\n" % error.msg)
     return rv
 
 if __name__ == "__main__":
index dfa1f8e..d7396f0 100755 (executable)
@@ -17,7 +17,8 @@ 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.
+local machine to generate documentation web pages.  Port number 0 can be
+used to get an arbitrary unused port.
 
 For platforms without a command line, "pydoc -g" starts the HTTP server
 and also pops up a little window for controlling it.
@@ -254,7 +255,7 @@ def synopsis(filename, cache={}):
         if info and 'b' in info[2]: # binary modules have to be imported
             try: module = imp.load_module('__temp__', file, filename, info[1:])
             except: return None
-            result = (module.__doc__ or '').splitlines()[0]
+            result = module.__doc__.splitlines()[0] if module.__doc__ else None
             del sys.modules['__temp__']
         else: # text modules can be directly examined
             result = source_synopsis(file)
@@ -1445,7 +1446,13 @@ def ttypager(text):
         getchar = lambda: sys.stdin.readline()[:-1][:1]
 
     try:
-        r = inc = os.environ.get('LINES', 25) - 1
+        try:
+            h = int(os.environ.get('LINES', 0))
+        except ValueError:
+            h = 0
+        if h <= 1:
+            h = 25
+        r = inc = h - 1
         sys.stdout.write(join(lines[:inc], '\n') + '\n')
         while lines[r:]:
             sys.stdout.write('-- more --')
@@ -1533,7 +1540,7 @@ def resolve(thing, forceload=0):
     """Given an object or a path to an object, get the object and its name."""
     if isinstance(thing, str):
         object = locate(thing, forceload)
-        if not object:
+        if object is None:
             raise ImportError, 'no Python documentation found for %r' % thing
         return object, thing
     else:
@@ -2013,7 +2020,7 @@ class ModuleScanner:
                         path = None
                 else:
                     module = loader.load_module(modname)
-                    desc = (module.__doc__ or '').splitlines()[0]
+                    desc = module.__doc__.splitlines()[0] if module.__doc__ else ''
                     path = getattr(module,'__file__',None)
                 if find(lower(modname + ' - ' + desc), key) >= 0:
                     callback(path, modname, desc)
@@ -2098,7 +2105,6 @@ pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
         def __init__(self, port, callback):
             host = 'localhost'
             self.address = (host, port)
-            self.url = 'http://%s:%d/' % (host, port)
             self.callback = callback
             self.base.__init__(self, self.address, self.handler)
 
@@ -2111,6 +2117,7 @@ pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
 
         def server_activate(self):
             self.base.server_activate(self)
+            self.url = 'http://%s:%d/' % (self.address[0], self.server_port)
             if self.callback: self.callback(self)
 
     DocServer.base = BaseHTTPServer.HTTPServer
@@ -2384,7 +2391,8 @@ def cli():
     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.
+    Start an HTTP server on the given port on the local machine.  Port
+    number 0 can be used to get an arbitrary unused port.
 
 %s -g
     Pop up a graphical interface for finding and serving documentation.
index a77071d..30dc44b 100644 (file)
@@ -1,80 +1,80 @@
 # -*- coding: utf-8 -*-
-# Autogenerated by Sphinx on Tue Nov 25 18:24:45 2014
+# Autogenerated by Sphinx on Sun May 10 13:12:18 2015
 topics = {'assert': u'\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 to\n\n   if __debug__:\n      if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that "__debug__" and "AssertionError" refer\nto 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 (command\nline option -O).  The current code generator emits no code for an\nassert statement when optimization is requested at compile time.  Note\nthat it is unnecessary to include the source code for the expression\nthat failed in the error message; it will be displayed as part of the\nstack trace.\n\nAssignments to "__debug__" are illegal.  The value for the built-in\nvariable is determined when the interpreter starts.\n',
- 'assignment': u'\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\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 is recursively defined as\nfollows.\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\n  object must be an iterable with the same number of items as there\n  are targets in the target list, and the items are assigned, from\n  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" statement in the\n    current code block: the name is bound to the object in the current\n    local namespace.\n\n  * Otherwise: the name is bound to the object in the current global\n    namespace.\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\n  square brackets: The object must be an iterable with the same number\n  of 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 always\n  set as an instance attribute, creating it if necessary.  Thus, the\n  two occurrences of "a.x" do not necessarily refer to the same\n  attribute: if the RHS expression refers to a class attribute, the\n  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 a plain integer.  If it is negative, the\n  sequence\'s length is added to it. The resulting value must be a\n  nonnegative integer less than the sequence\'s length, and the\n  sequence is asked to assign the assigned object to its item with\n  that index.  If the index is out of range, "IndexError" is raised\n  (assignment to a subscripted sequence cannot add new items to a\n  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* If the target is a slicing: The primary expression in the\n  reference is evaluated.  It should yield a mutable sequence object\n  (such as a list).  The assigned object should be a sequence object\n  of the same type.  Next, the lower and upper bound expressions are\n  evaluated, insofar they are present; defaults are zero and the\n  sequence\'s length.  The bounds should evaluate to (small) integers.\n  If either bound is negative, the sequence\'s length is added to it.\n  The resulting bounds are clipped to lie between zero and the\n  sequence\'s length, inclusive.  Finally, the sequence object is asked\n  to replace the slice with the items of the assigned sequence.  The\n  length of the slice may be different from the length of the assigned\n  sequence, thus changing the length of the target sequence, if the\n  object 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\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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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': u'\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, with leading underscores removed and a single underscore\ninserted, in front of the name.  For example, the identifier "__spam"\noccurring in a class named "Ham" will be transformed to "_Ham__spam".\nThis transformation is independent of the syntactical context in which\nthe identifier is used.  If the transformed name is extremely long\n(longer than 255 characters), implementation defined truncation may\nhappen. If the class name consists only of underscores, no\ntransformation is done.\n',
- 'atom-literals': u"\nLiterals\n********\n\nPython supports string literals and various numeric literals:\n\n   literal ::= stringliteral | integer | longinteger\n               | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\ninteger, long integer, floating point number, complex number) with the\ngiven value.  The value may be approximated in the case of floating\npoint and imaginary (complex) literals.  See section *Literals* for\ndetails.\n\nAll literals correspond to immutable data types, and hence the\nobject's identity is less important than its value.  Multiple\nevaluations of literals with the same value (either the same\noccurrence in the program text or a different occurrence) may obtain\nthe same object or a different object with the same value.\n",
- 'attribute-access': u'\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") for\nclass 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. This\n   method should return the (computed) attribute value or raise an\n   "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 for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   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 in new-style classes.\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 not simply execute "self.name = value" --- this would cause\n   a recursive call to itself.  Instead, it should insert the value in\n   the dictionary of instance attributes, e.g., "self.__dict__[name] =\n   value".  For new-style classes, rather than accessing the instance\n   dictionary, it should call the base class method with the same\n   name, for example, "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\n\nMore attribute access for new-style classes\n===========================================\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See *Special method lookup for new-style\n     classes*.\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 an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  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 "AttributeError"\n   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, it\nis 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.  Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe 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 a new-style object instance, "a.x" is transformed\n   into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a new-style class, "A.x" is transformed into the\n   call: "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 "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\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__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented 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 both old and new-style classes have a\ndictionary for attribute storage.  This wastes space for objects\nhaving very few instance variables.  The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition.  The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable.  Space is saved because *__dict__* is\nnot created for each instance.\n\n__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   new-style class, *__slots__* reserves space for the declared\n   variables and prevents the automatic creation of *__dict__* and\n   *__weakref__* for each instance.\n\n   New in version 2.2.\n\nNotes on using *__slots__*\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  Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n  *__slots__* declaration would not enable the assignment of new\n  attributes not specifically listed in the sequence of instance\n  variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n  Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n  *__slots__* declaration would not enable support for weak\n  references.\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\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This 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 "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may 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  Changed in version 2.6: Previously, *__class__* assignment raised an\n  error if either new or old class had *__slots__*.\n',
+ 'assignment': u'\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\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 is recursively defined as\nfollows.\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\n  object must be an iterable with the same number of items as there\n  are targets in the target list, and the items are assigned, from\n  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" statement in the\n    current code block: the name is bound to the object in the current\n    local namespace.\n\n  * Otherwise: the name is bound to the object in the current global\n    namespace.\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\n  square brackets: The object must be an iterable with the same number\n  of 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 always\n  set as an instance attribute, creating it if necessary.  Thus, the\n  two occurrences of "a.x" do not necessarily refer to the same\n  attribute: if the RHS expression refers to a class attribute, the\n  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 a plain integer.  If it is negative, the\n  sequence\'s length is added to it. The resulting value must be a\n  nonnegative integer less than the sequence\'s length, and the\n  sequence is asked to assign the assigned object to its item with\n  that index.  If the index is out of range, "IndexError" is raised\n  (assignment to a subscripted sequence cannot add new items to a\n  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* If the target is a slicing: The primary expression in the\n  reference is evaluated.  It should yield a mutable sequence object\n  (such as a list).  The assigned object should be a sequence object\n  of the same type.  Next, the lower and upper bound expressions are\n  evaluated, insofar they are present; defaults are zero and the\n  sequence\'s length.  The bounds should evaluate to (small) integers.\n  If either bound is negative, the sequence\'s length is added to it.\n  The resulting bounds are clipped to lie between zero and the\n  sequence\'s length, inclusive.  Finally, the sequence object is asked\n  to replace the slice with the items of the assigned sequence.  The\n  length of the slice may be different from the length of the assigned\n  sequence, thus changing the length of the target sequence, if the\n  object 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\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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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': u'\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name.  See section Identifiers\nand keywords for lexical definition and section Naming and binding for\ndocumentation 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, with leading underscores removed and a single underscore\ninserted, in front of the name.  For example, the identifier "__spam"\noccurring in a class named "Ham" will be transformed to "_Ham__spam".\nThis transformation is independent of the syntactical context in which\nthe identifier is used.  If the transformed name is extremely long\n(longer than 255 characters), implementation defined truncation may\nhappen. If the class name consists only of underscores, no\ntransformation is done.\n',
+ 'atom-literals': u"\nLiterals\n********\n\nPython supports string literals and various numeric literals:\n\n   literal ::= stringliteral | integer | longinteger\n               | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\ninteger, long integer, floating point number, complex number) with the\ngiven value.  The value may be approximated in the case of floating\npoint and imaginary (complex) literals.  See section Literals for\ndetails.\n\nAll literals correspond to immutable data types, and hence the\nobject's identity is less important than its value.  Multiple\nevaluations of literals with the same value (either the same\noccurrence in the program text or a different occurrence) may obtain\nthe same object or a different object with the same value.\n",
+ 'attribute-access': u'\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") for\nclass 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. This\n   method should return the (computed) attribute value or raise an\n   "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 for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   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 in new-style classes.\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 not simply execute "self.name = value" --- this would cause\n   a recursive call to itself.  Instead, it should insert the value in\n   the dictionary of instance attributes, e.g., "self.__dict__[name] =\n   value".  For new-style classes, rather than accessing the instance\n   dictionary, it should call the base class method with the same\n   name, for example, "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\n\nMore attribute access for new-style classes\n===========================================\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See Special method lookup for new-style\n     classes.\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 an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  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 "AttributeError"\n   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, it\nis 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.  Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe 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 a new-style object instance, "a.x" is transformed\n   into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a new-style class, "A.x" is transformed into the\n   call: "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 "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\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__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented 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 both old and new-style classes have a\ndictionary for attribute storage.  This wastes space for objects\nhaving very few instance variables.  The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition.  The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable.  Space is saved because *__dict__* is\nnot created for each instance.\n\n__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   new-style class, *__slots__* reserves space for the declared\n   variables and prevents the automatic creation of *__dict__* and\n   *__weakref__* for each instance.\n\n   New in version 2.2.\n\nNotes on using *__slots__*\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  Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n  *__slots__* declaration would not enable the assignment of new\n  attributes not specifically listed in the sequence of instance\n  variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n  Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n  *__slots__* declaration would not enable support for weak\n  references.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (Implementing Descriptors) for each variable name.  As a\n  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\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This 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 "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may 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  Changed in version 2.6: Previously, *__class__* assignment raised an\n  error if either new or old class had *__slots__*.\n',
  'attribute-references': u'\nAttribute references\n********************\n\nAn attribute reference is a primary followed by a period and a name:\n\n   attributeref ::= primary "." identifier\n\nThe primary must evaluate to an object of a type that supports\nattribute references, e.g., a module, list, or an instance.  This\nobject is then asked to produce the attribute whose name is the\nidentifier.  If this attribute is not available, the exception\n"AttributeError" is raised. Otherwise, the type and value of the\nobject produced is determined by the object.  Multiple evaluations of\nthe same attribute reference may yield different objects.\n',
- 'augassign': u'\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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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',
- 'binary': u'\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels.  Note that some of these operations also apply to certain non-\nnumeric types.  Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n   m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n              | m_expr "%" u_expr\n   a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe "*" (multiplication) operator yields the product of its arguments.\nThe arguments must either both be numbers, or one argument must be an\ninteger (plain or long) and the other must be a sequence. In the\nformer case, the numbers are converted to a common type and then\nmultiplied together.  In the latter case, sequence repetition is\nperformed; a negative repetition factor yields an empty sequence.\n\nThe "/" (division) and "//" (floor division) operators yield the\nquotient of their arguments.  The numeric arguments are first\nconverted to a common type. Plain or long integer division yields an\ninteger of the same type; the result is that of mathematical division\nwith the \'floor\' function applied to the result. Division by zero\nraises the "ZeroDivisionError" exception.\n\nThe "%" (modulo) operator yields the remainder from the division of\nthe first argument by the second.  The numeric arguments are first\nconverted to a common type.  A zero right argument raises the\n"ZeroDivisionError" exception.  The arguments may be floating point\nnumbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +\n0.34".)  The modulo operator always yields a result with the same sign\nas its second operand (or zero); the absolute value of the result is\nstrictly smaller than the absolute value of the second operand [2].\n\nThe integer division and modulo operators are connected by the\nfollowing identity: "x == (x/y)*y + (x%y)".  Integer division and\nmodulo are also connected with the built-in function "divmod()":\n"divmod(x, y) == (x/y, x%y)".  These identities don\'t hold for\nfloating point numbers; there similar identities hold approximately\nwhere "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" [3].\n\nIn addition to performing the modulo operation on numbers, the "%"\noperator is also overloaded by string and unicode objects to perform\nstring formatting (also known as interpolation). The syntax for string\nformatting is described in the Python Library Reference, section\n*String Formatting Operations*.\n\nDeprecated since version 2.3: The floor division operator, the modulo\noperator, and the "divmod()" function are no longer defined for\ncomplex numbers.  Instead, convert to a floating point number using\nthe "abs()" function if appropriate.\n\nThe "+" (addition) operator yields the sum of its arguments. The\narguments must either both be numbers or both sequences of the same\ntype.  In the former case, the numbers are converted to a common type\nand then added together.  In the latter case, the sequences are\nconcatenated.\n\nThe "-" (subtraction) operator yields the difference of its arguments.\nThe numeric arguments are first converted to a common type.\n',
+ 'augassign': u'\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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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',
+ 'binary': u'\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels.  Note that some of these operations also apply to certain non-\nnumeric types.  Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n   m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n              | m_expr "%" u_expr\n   a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe "*" (multiplication) operator yields the product of its arguments.\nThe arguments must either both be numbers, or one argument must be an\ninteger (plain or long) and the other must be a sequence. In the\nformer case, the numbers are converted to a common type and then\nmultiplied together.  In the latter case, sequence repetition is\nperformed; a negative repetition factor yields an empty sequence.\n\nThe "/" (division) and "//" (floor division) operators yield the\nquotient of their arguments.  The numeric arguments are first\nconverted to a common type. Plain or long integer division yields an\ninteger of the same type; the result is that of mathematical division\nwith the \'floor\' function applied to the result. Division by zero\nraises the "ZeroDivisionError" exception.\n\nThe "%" (modulo) operator yields the remainder from the division of\nthe first argument by the second.  The numeric arguments are first\nconverted to a common type.  A zero right argument raises the\n"ZeroDivisionError" exception.  The arguments may be floating point\nnumbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +\n0.34".)  The modulo operator always yields a result with the same sign\nas its second operand (or zero); the absolute value of the result is\nstrictly smaller than the absolute value of the second operand [2].\n\nThe integer division and modulo operators are connected by the\nfollowing identity: "x == (x/y)*y + (x%y)".  Integer division and\nmodulo are also connected with the built-in function "divmod()":\n"divmod(x, y) == (x/y, x%y)".  These identities don\'t hold for\nfloating point numbers; there similar identities hold approximately\nwhere "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" [3].\n\nIn addition to performing the modulo operation on numbers, the "%"\noperator is also overloaded by string and unicode objects to perform\nstring formatting (also known as interpolation). The syntax for string\nformatting is described in the Python Library Reference, section\nString Formatting Operations.\n\nDeprecated since version 2.3: The floor division operator, the modulo\noperator, and the "divmod()" function are no longer defined for\ncomplex numbers.  Instead, convert to a floating point number using\nthe "abs()" function if appropriate.\n\nThe "+" (addition) operator yields the sum of its arguments. The\narguments must either both be numbers or both sequences of the same\ntype.  In the former case, the numbers are converted to a common type\nand then added together.  In the latter case, the sequences are\nconcatenated.\n\nThe "-" (subtraction) operator yields the difference of its arguments.\nThe numeric arguments are first converted to a common type.\n',
  'bitwise': u'\nBinary bitwise operations\n*************************\n\nEach of the three bitwise operations has a different priority level:\n\n   and_expr ::= shift_expr | and_expr "&" shift_expr\n   xor_expr ::= and_expr | xor_expr "^" and_expr\n   or_expr  ::= xor_expr | or_expr "|" xor_expr\n\nThe "&" operator yields the bitwise AND of its arguments, which must\nbe plain or long integers.  The arguments are converted to a common\ntype.\n\nThe "^" operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be plain or long integers.  The arguments are\nconverted to a common type.\n\nThe "|" operator yields the bitwise (inclusive) OR of its arguments,\nwhich must be plain or long integers.  The arguments are converted to\na common type.\n',
- 'bltin-code-objects': u'\nCode Objects\n************\n\nCode objects are used by the implementation to represent "pseudo-\ncompiled" executable Python code such as a function body. They differ\nfrom function objects because they don\'t contain a reference to their\nglobal execution environment.  Code objects are returned by the built-\nin "compile()" function and can be extracted from function objects\nthrough their "func_code" attribute. See also the "code" module.\n\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the "exec" statement or the built-in "eval()"\nfunction.\n\nSee *The standard type hierarchy* for more information.\n',
- 'bltin-ellipsis-object': u'\nThe Ellipsis Object\n*******************\n\nThis object is used by extended slice notation (see *Slicings*).  It\nsupports no special operations.  There is exactly one ellipsis object,\nnamed "Ellipsis" (a built-in name).\n\nIt is written as "Ellipsis".  When in a subscript, it can also be\nwritten as "...", for example "seq[...]".\n',
+ 'bltin-code-objects': u'\nCode Objects\n************\n\nCode objects are used by the implementation to represent "pseudo-\ncompiled" executable Python code such as a function body. They differ\nfrom function objects because they don\'t contain a reference to their\nglobal execution environment.  Code objects are returned by the built-\nin "compile()" function and can be extracted from function objects\nthrough their "func_code" attribute. See also the "code" module.\n\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the "exec" statement or the built-in "eval()"\nfunction.\n\nSee The standard type hierarchy for more information.\n',
+ 'bltin-ellipsis-object': u'\nThe Ellipsis Object\n*******************\n\nThis object is used by extended slice notation (see Slicings).  It\nsupports no special operations.  There is exactly one ellipsis object,\nnamed "Ellipsis" (a built-in name).\n\nIt is written as "Ellipsis".  When in a subscript, it can also be\nwritten as "...", for example "seq[...]".\n',
  'bltin-null-object': u'\nThe Null Object\n***************\n\nThis object is returned by functions that don\'t explicitly return a\nvalue.  It supports no special operations.  There is exactly one null\nobject, named "None" (a built-in name).\n\nIt is written as "None".\n',
  'bltin-type-objects': u'\nType Objects\n************\n\nType objects represent the various object types.  An object\'s type is\naccessed by the built-in function "type()".  There are no special\noperations on types.  The standard module "types" defines names for\nall standard built-in types.\n\nTypes are written like this: "<type \'int\'>".\n',
  'booleans': u'\nBoolean operations\n******************\n\n   or_test  ::= and_test | or_test "or" and_test\n   and_test ::= not_test | and_test "and" not_test\n   not_test ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: "False", "None", numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets).  All other values are interpreted\nas true.  (See the "__nonzero__()" special method for a way to change\nthis.)\n\nThe operator "not" yields "True" if its argument is false, "False"\notherwise.\n\nThe expression "x and y" first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression "x or y" first evaluates *x*; if *x* is true, its value\nis returned; otherwise, *y* is evaluated and the resulting value is\nreturned.\n\n(Note that neither "and" nor "or" restrict the value and type they\nreturn to "False" and "True", but rather return the last evaluated\nargument. This is sometimes useful, e.g., if "s" is a string that\nshould be replaced by a default value if it is empty, the expression\n"s or \'foo\'" yields the desired value.  Because "not" has to invent a\nvalue anyway, it does not bother to return a value of the same type as\nits argument, so e.g., "not \'foo\'" yields "False", not "\'\'".)\n',
  'break': u'\nThe "break" statement\n*********************\n\n   break_stmt ::= "break"\n\n"break" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition within that\nloop.\n\nIt terminates the nearest enclosing loop, skipping the optional "else"\nclause 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 "finally"\nclause, that "finally" clause is executed before really leaving the\nloop.\n',
  'callable-types': u'\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': u'\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 [","]\n            | expression genexpr_for] ")"\n   argument_list        ::= positional_arguments ["," keyword_arguments]\n                       ["," "*" expression] ["," keyword_arguments]\n                       ["," "**" expression]\n                     | keyword_arguments ["," "*" expression]\n                       ["," "**" 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 certain class instances\nthemselves are callable; extensions may define additional callable\nobject types).  All argument expressions are evaluated before the call\nis attempted.  Please refer to section *Function definitions* for the\nsyntax 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 "TypeError"\nexception is raised.  Otherwise, the list of filled slots is used as\nthe 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 parse\ntheir 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 formal\nparameter 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, "expression"\nmust evaluate to an iterable.  Elements from this iterable are treated\nas if they were additional positional arguments; if there are\npositional arguments *x1*, ..., *xN*, and "expression" evaluates to a\nsequence *y1*, ..., *yM*, this is equivalent to a call with M+N\npositional 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" syntax\nto be used in the same call, so in practice this confusion does not\narise.\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, a\n"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.  Formal parameters using the syntax "(sublist)" cannot be used\nas keyword argument names; the outermost sublist corresponds to a\nsingle unnamed argument slot, and the argument value is assigned to\nthe sublist using the usual tuple assignment rules after all other\nparameter processing is done.\n\nA call always returns some value, possibly "None", unless it raises an\nexception.  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 the\n   same as if that method was called.\n',
- 'class': u'\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances.  To create instance\nvariables, they can be set in a method with "self.name = value".  Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an 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\n    function body is transformed into the function\'s "__doc__"\n    attribute and 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': u'\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 only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound 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", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects need not have the same type. If both are\nnumbers, they are converted to a common type.  Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section *Special method names*.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n  equivalents (the result of the built-in function "ord()") of their\n  characters. Unicode and 8-bit strings are fully interoperable in\n  this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n  of 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, "cmp([1,2,x], [1,2,y])" returns\n  the same as "cmp(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 their sorted\n  (key, value) lists compare equal. [5] Outcomes other than equality\n  are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n  are the same object; the choice whether one object is considered\n  smaller or larger than another one is made arbitrarily but\n  consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership.  "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise.  "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object.  However, it make sense\nfor many other object types to support membership tests without being\na sequence.  In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*.  An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin 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 == z"\nis produced while iterating over "y".  If an exception is raised\nduring 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 y" is\ntrue if and only if *x* and *y* are the same object.  "x is not y"\nyields the inverse truth value. [7]\n',
- 'compound': u'\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 control\nflow constructs.  "try" specifies exception handlers and/or cleanup\ncode for a group of statements.  Function and class definitions are\nalso syntactically compound 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" statements 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                     | decorated\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 a\n"DEDENT". Also note that optional continuation clauses always begin\nwith 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 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" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n\n\nThe "for" statement\n===================\n\nThe "for" statement is used to iterate over the elements of a sequence\n(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, and then the suite is executed.  When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there was no next\nitem.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop.  Hint: the built-in function "range()" returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s "for i := a to b\ndo"; e.g., "range(3)" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (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" | ",") identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n"try"..."except"..."finally" did not work. "try"..."except" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified in that except clause, if present, and the except\nclause\'s suite is executed.  All except clauses must have an\nexecutable block.  When the end of this block is reached, execution\ncontinues normally after the entire try statement.  (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the "sys" module:\n"sys.exc_type" receives the object identifying the exception;\n"sys.exc_value" receives the exception\'s parameter;\n"sys.exc_traceback" receives a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. These details are also available through the\n"sys.exc_info()" function, which returns a tuple "(exc_type,\nexc_value, exc_traceback)".  Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program.  As of Python 1.5, the variables 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\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\nNew in version 2.5.\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n     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, three\n   "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 reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   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\nNote: In Python 2.5, the "with" statement is only allowed when the\n  "with_statement" feature has been enabled.  It is always enabled in\n  Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   decorated      ::= decorators (classdef | funcdef)\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   funcdef        ::= "def" funcname "(" [parameter_list] ")" ":" suite\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" identifier ["," "**" identifier]\n                      | "**" identifier\n                      | defparameter [","] )\n   defparameter   ::= parameter ["=" expression]\n   sublist        ::= parameter ("," parameter)* [","]\n   parameter      ::= identifier | "(" sublist ")"\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 top-level *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 must also have a default value --- this is a syntactic\nrestriction 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 the 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 any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements.\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    ::= "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section *Naming and binding*), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances.  To create instance\nvariables, they can be set in a method with "self.name = value".  Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an 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\n    function body is transformed into the function\'s "__doc__"\n    attribute and 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': u'\nWith Statement Context Managers\n*******************************\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section *The with\nstatement*), but can also be used by directly invoking their methods.\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: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n',
+ 'calls': u'\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 [","]\n            | expression genexpr_for] ")"\n   argument_list        ::= positional_arguments ["," keyword_arguments]\n                       ["," "*" expression] ["," keyword_arguments]\n                       ["," "**" expression]\n                     | keyword_arguments ["," "*" expression]\n                       ["," "**" 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 certain class instances\nthemselves are callable; extensions may define additional callable\nobject types).  All argument expressions are evaluated before the call\nis attempted.  Please refer to section Function definitions for the\nsyntax 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 "TypeError"\nexception is raised.  Otherwise, the list of filled slots is used as\nthe 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 parse\ntheir 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 formal\nparameter 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, "expression"\nmust evaluate to an iterable.  Elements from this iterable are treated\nas if they were additional positional arguments; if there are\npositional arguments *x1*, ..., *xN*, and "expression" evaluates to a\nsequence *y1*, ..., *yM*, this is equivalent to a call with M+N\npositional 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" syntax\nto be used in the same call, so in practice this confusion does not\narise.\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, a\n"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.  Formal parameters using the syntax "(sublist)" cannot be used\nas keyword argument names; the outermost sublist corresponds to a\nsingle unnamed argument slot, and the argument value is assigned to\nthe sublist using the usual tuple assignment rules after all other\nparameter processing is done.\n\nA call always returns some value, possibly "None", unless it raises an\nexception.  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 the\n   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 the\n   same as if that method was called.\n',
+ 'class': u'\nClass definitions\n*****************\n\nA class definition defines a class object (see section The standard\ntype hierarchy):\n\n   classdef    ::= "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section Naming and binding), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances.  To create instance\nvariables, they can be set in a method with "self.name = value".  Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an 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\n    function body is transformed into the function\'s "__doc__"\n    attribute and 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': u'\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 only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound 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", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects need not have the same type. If both are\nnumbers, they are converted to a common type.  Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section Special method names.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n  equivalents (the result of the built-in function "ord()") of their\n  characters. Unicode and 8-bit strings are fully interoperable in\n  this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n  of 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, "cmp([1,2,x], [1,2,y])" returns\n  the same as "cmp(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 their sorted\n  (key, value) lists compare equal. [5] Outcomes other than equality\n  are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n  are the same object; the choice whether one object is considered\n  smaller or larger than another one is made arbitrarily but\n  consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership.  "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise.  "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object.  However, it make sense\nfor many other object types to support membership tests without being\na sequence.  In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*.  An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin 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 == z"\nis produced while iterating over "y".  If an exception is raised\nduring 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 y" is\ntrue if and only if *x* and *y* are the same object.  "x is not y"\nyields the inverse truth value. [7]\n',
+ 'compound': u'\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 control\nflow constructs.  "try" specifies exception handlers and/or cleanup\ncode for a group of statements.  Function and class definitions are\nalso syntactically compound 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" statements 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                     | decorated\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 a\n"DEDENT". Also note that optional continuation clauses always begin\nwith 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 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" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n\n\nThe "for" statement\n===================\n\nThe "for" statement is used to iterate over the elements of a sequence\n(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, and then the suite is executed.  When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there was no next\nitem.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop.  Hint: the built-in function "range()" returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s "for i := a to b\ndo"; e.g., "range(3)" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (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" | ",") identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n"try"..."except"..."finally" did not work. "try"..."except" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified in that except clause, if present, and the except\nclause\'s suite is executed.  All except clauses must have an\nexecutable block.  When the end of this block is reached, execution\ncontinues normally after the entire try statement.  (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the "sys" module:\n"sys.exc_type" receives the object identifying the exception;\n"sys.exc_value" receives the exception\'s parameter;\n"sys.exc_traceback" receives a traceback object (see section The\nstandard type hierarchy) identifying the point in the program where\nthe exception occurred. These details are also available through the\n"sys.exc_info()" function, which returns a tuple "(exc_type,\nexc_value, exc_traceback)".  Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program.  As of Python 1.5, the variables 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\n\nAdditional information on exceptions can be found in section\nExceptions, and information on using the "raise" statement to generate\nexceptions may be found in section The raise statement.\n\n\nThe "with" statement\n====================\n\nNew in version 2.5.\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n     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, three\n   "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 reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   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\nNote: In Python 2.5, the "with" statement is only allowed when the\n  "with_statement" feature has been enabled.  It is always enabled in\n  Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection The standard type hierarchy):\n\n   decorated      ::= decorators (classdef | funcdef)\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   funcdef        ::= "def" funcname "(" [parameter_list] ")" ":" suite\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" identifier ["," "**" identifier]\n                      | "**" identifier\n                      | defparameter [","] )\n   defparameter   ::= parameter ["=" expression]\n   sublist        ::= parameter ("," parameter)* [","]\n   parameter      ::= identifier | "(" sublist ")"\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 top-level *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 must also have a default value --- this is a syntactic\nrestriction 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 the 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 Calls.\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values.  If the form ""*identifier"" is\npresent, it is initialized to a tuple receiving any excess positional\nparameters, defaulting to the empty tuple.  If the form\n""**identifier"" is present, it is initialized to a new dictionary\nreceiving any excess keyword arguments, defaulting to a new empty\ndictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section Lambdas.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements.\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    ::= "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [expression_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  It first evaluates the\ninheritance list, if present.  Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing.  The class\'s suite is then executed in a new execution\nframe (see section Naming and binding), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.)  When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary.  The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances.  To create instance\nvariables, they can be set in a method with "self.name = value".  Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results.  For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions.  The evaluation rules for the decorator\nexpressions are the same as for functions.  The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an 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\n    function body is transformed into the function\'s "__doc__"\n    attribute and 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': u'\nWith Statement Context Managers\n*******************************\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section The with\nstatement), but can also be used by directly invoking their methods.\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: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n',
  'continue': u'\nThe "continue" statement\n************************\n\n   continue_stmt ::= "continue"\n\n"continue" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition or "finally"\nclause within that loop.  It continues with the next cycle of the\nnearest 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': u'\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," the arguments\nare coerced using the coercion rules listed at  *Coercion rules*.  If\nboth arguments are standard numeric types, the following coercions are\napplied:\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\n  other is converted to floating point;\n\n* otherwise, if either argument is a long integer, the other is\n  converted to long integer;\n\n* otherwise, both must be plain integers and no conversion is\n  necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions can define their own\ncoercions.\n',
- 'customization': u'\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 an\n   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, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".  As a special constraint on\n   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, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__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 is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_traceback" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     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.exc_traceback" or "sys.last_traceback".  Circular references\n     which are garbage are detected when the option cycle detector is\n     enabled (it\'s on by default), but can only be cleaned up if there\n     are no Python-level "__del__()" methods involved. Refer to the\n     documentation 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\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python 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\n   See also the *-R* command-line option.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function and by string conversions\n   (reverse quotes) to compute the "official" string representation of\n   an object.  If at all possible, this should look like a valid\n   Python expression that could be used to recreate an object with the\n   same value (given an appropriate environment).  If this is not\n   possible, a string of the form "<...some useful description...>"\n   should be returned.  The return value must be a string object. If a\n   class defines "__repr__()" but not "__str__()", then "__repr__()"\n   is also used when an "informal" string representation of instances\n   of that class is 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   statement to compute the "informal" string representation of an\n   object.  This differs from "__repr__()" in that it does not have to\n   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.__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   New in version 2.1.\n\n   These are the so-called "rich comparison" methods, and are called\n   for comparison operators in preference to "__cmp__()" below. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call "x.__ne__(y)",\n   "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result 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 the\n   paragraph on "__hash__()" for some important notes on creating\n   *hashable* objects which support custom comparison operations and\n   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 other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own 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.__cmp__(self, other)\n\n   Called by comparison operations if rich comparison (see above) is\n   not defined.  Should return a negative integer if "self < other",\n   zero if "self == other", a positive integer if "self > other".  If\n   no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n   class instances are compared by object identity ("address").  See\n   also the description of "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys. (Note: the\n   restriction that exceptions are not propagated by "__cmp__()" has\n   been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n   Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   If a class does not define a "__cmp__()" or "__eq__()" method it\n   should not define a "__hash__()" operation either; if it defines\n   "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n   not be usable in hashed collections.  If a class defines mutable\n   objects and implements a "__cmp__()" or "__eq__()" method, it\n   should not implement "__hash__()", since hashable collection\n   implementations require that a object\'s hash value is immutable (if\n   the object\'s hash value changes, it will be in the wrong hash\n   bucket).\n\n   User-defined classes have "__cmp__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns a result derived from\n   "id(x)".\n\n   Classes which inherit a "__hash__()" method from a parent class but\n   change the meaning of "__cmp__()" or "__eq__()" such that the hash\n   value returned is no longer appropriate (e.g. by switching to a\n   value-based concept of equality instead of the default identity\n   based equality) can explicitly flag themselves as being unhashable\n   by setting "__hash__ = None" in the class definition. Doing so\n   means that not only will instances of the class raise an\n   appropriate "TypeError" when a program attempts to retrieve their\n   hash value, but they will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)"\n   (unlike classes which define their own "__hash__()" to explicitly\n   raise "TypeError").\n\n   Changed in version 2.5: "__hash__()" may now also return a long\n   integer object; the 32-bit integer is then derived from the hash of\n   that object.\n\n   Changed in version 2.6: "__hash__" may now be set to "None" to\n   explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True", or their integer\n   equivalents "0" or "1".  When this method is not defined,\n   "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero. If a class defines\n   neither "__len__()" nor "__nonzero__()", all its instances are\n   considered true.\n\nobject.__unicode__(self)\n\n   Called to implement "unicode()" built-in; should return a Unicode\n   object. When this method is not defined, string conversion is\n   attempted, and the result of string conversion is converted to\n   Unicode using the system default encoding.\n',
+ 'conversions': u'\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," the arguments\nare coerced using the coercion rules listed at  Coercion rules.  If\nboth arguments are standard numeric types, the following coercions are\napplied:\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\n  other is converted to floating point;\n\n* otherwise, if either argument is a long integer, the other is\n  converted to long integer;\n\n* otherwise, both must be plain integers and no conversion is\n  necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions can define their own\ncoercions.\n',
+ 'customization': u'\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 an\n   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 after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  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, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customise\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "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, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__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 is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_traceback" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     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.exc_traceback" or "sys.last_traceback".  Circular references\n     which are garbage are detected when the option cycle detector is\n     enabled (it\'s on by default), but can only be cleaned up if there\n     are no Python-level "__del__()" methods involved. Refer to the\n     documentation 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\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python 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\n   See also the "-R" command-line option.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function and by string conversions\n   (reverse quotes) to compute the "official" string representation of\n   an object.  If at all possible, this should look like a valid\n   Python expression that could be used to recreate an object with the\n   same value (given an appropriate environment).  If this is not\n   possible, a string of the form "<...some useful description...>"\n   should be returned.  The return value must be a string object. If a\n   class defines "__repr__()" but not "__str__()", then "__repr__()"\n   is also used when an "informal" string representation of instances\n   of that class is 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   statement to compute the "informal" string representation of an\n   object.  This differs from "__repr__()" in that it does not have to\n   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.__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   New in version 2.1.\n\n   These are the so-called "rich comparison" methods, and are called\n   for comparison operators in preference to "__cmp__()" below. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call "x.__ne__(y)",\n   "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result 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 the\n   paragraph on "__hash__()" for some important notes on creating\n   *hashable* objects which support custom comparison operations and\n   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 other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own 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.__cmp__(self, other)\n\n   Called by comparison operations if rich comparison (see above) is\n   not defined.  Should return a negative integer if "self < other",\n   zero if "self == other", a positive integer if "self > other".  If\n   no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n   class instances are compared by object identity ("address").  See\n   also the description of "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys. (Note: the\n   restriction that exceptions are not propagated by "__cmp__()" has\n   been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n   Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   If a class does not define a "__cmp__()" or "__eq__()" method it\n   should not define a "__hash__()" operation either; if it defines\n   "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n   not be usable in hashed collections.  If a class defines mutable\n   objects and implements a "__cmp__()" or "__eq__()" method, it\n   should not implement "__hash__()", since hashable collection\n   implementations require that a object\'s hash value is immutable (if\n   the object\'s hash value changes, it will be in the wrong hash\n   bucket).\n\n   User-defined classes have "__cmp__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns a result derived from\n   "id(x)".\n\n   Classes which inherit a "__hash__()" method from a parent class but\n   change the meaning of "__cmp__()" or "__eq__()" such that the hash\n   value returned is no longer appropriate (e.g. by switching to a\n   value-based concept of equality instead of the default identity\n   based equality) can explicitly flag themselves as being unhashable\n   by setting "__hash__ = None" in the class definition. Doing so\n   means that not only will instances of the class raise an\n   appropriate "TypeError" when a program attempts to retrieve their\n   hash value, but they will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)"\n   (unlike classes which define their own "__hash__()" to explicitly\n   raise "TypeError").\n\n   Changed in version 2.5: "__hash__()" may now also return a long\n   integer object; the 32-bit integer is then derived from the hash of\n   that object.\n\n   Changed in version 2.6: "__hash__" may now be set to "None" to\n   explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True", or their integer\n   equivalents "0" or "1".  When this method is not defined,\n   "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero. If a class defines\n   neither "__len__()" nor "__nonzero__()", all its instances are\n   considered true.\n\nobject.__unicode__(self)\n\n   Called to implement "unicode()" built-in; should return a Unicode\n   object. When this method is not defined, string conversion is\n   attempted, and the result of string conversion is converted to\n   Unicode using the system default encoding.\n',
  'debugger': u'\n"pdb" --- The Python Debugger\n*****************************\n\n**Source code:** Lib/pdb.py\n\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 reading\nthe source.  The extension interface uses the modules "bdb" and "cmd".\n\nThe debugger\'s prompt is "(Pdb)". Typical usage to run a program under\ncontrol 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.  For\nexample:\n\n   python -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 2.4: Restarting post-mortem behavior added.\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 "c" 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[, locals]])\n\n   Execute the *statement* (given as a string) under debugger control.\n   The debugger prompt appears before any code is executed; you can\n   set breakpoints and type "continue", or you can step through the\n   statement using "step" or "next" (all these commands are explained\n   below).  The optional *globals* and *locals* arguments specify the\n   environment in which the code is executed; by default the\n   dictionary of the module "__main__" is used.  (See the explanation\n   of the "exec" statement or the "eval()" built-in function.)\n\npdb.runeval(expression[, globals[, locals]])\n\n   Evaluate the *expression* (given as a string) under debugger\n   control.  When "runeval()" returns, it returns the value of the\n   expression.  Otherwise this function is similar to "run()".\n\npdb.runcall(function[, argument, ...])\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])\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 instantiating\nthe "Pdb" class and calling the method of the same name.  If you want\nto access further features, you have to do this yourself:\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 2.7: The *skip* argument.\n\n   run(statement[, globals[, locals]])\n   runeval(expression[, globals[, locals]])\n   runcall(function[, argument, ...])\n   set_trace()\n\n      See the documentation for the functions explained above.\n',
  'del': u'\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 than 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\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested block.\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',
- 'dict': u'\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',
+ 'dict': u'\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': u'\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\nIf "exec" is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n"SyntaxError" unless the exec explicitly specifies the local namespace\nfor the "exec".  (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames.  Names may be resolved in the local and global namespaces of\nthe caller.  Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
- 'else': u'\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': u'\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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof.  The instance can be\nreceived by the handler and can carry additional information about the\nexceptional condition.\n\nExceptions can also be identified by strings, in which case the\n"except" clause is selected by object identity.  An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API.  Their\n  contents may change from one version of Python to the next without\n  warning and should not be relied on by code which will run under\n  multiple 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\n    these operations is not available at the time the module is\n    compiled.\n',
- 'exec': u'\nThe "exec" statement\n********************\n\n   exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]\n\nThis statement supports dynamic execution of Python code.  The first\nexpression should evaluate to either a Unicode string, a *Latin-1*\nencoded string, an open file object, a code object, or a tuple.  If it\nis a string, the string is parsed as a suite of Python statements\nwhich is then executed (unless a syntax error occurs). [1] If it is an\nopen file, the file is parsed until EOF and executed. If it is a code\nobject, it is simply executed.  For the interpretation of a tuple, see\nbelow.  In all cases, the code that\'s executed is expected to be valid\nas file input (see section *File input*).  Be aware that the "return"\nand "yield" statements may not be used outside of function definitions\neven within the context of code passed to the "exec" statement.\n\nIn all cases, if the optional parts are omitted, the code is executed\nin the current scope.  If only the first expression after "in" is\nspecified, it should be a dictionary, which will be used for both the\nglobal and the local variables.  If two expressions are given, they\nare used for the global and local variables, respectively. If\nprovided, *locals* can be any mapping object. Remember that at module\nlevel, globals and locals are the same dictionary. If two separate\nobjects are given as *globals* and *locals*, the code will be executed\nas if it were embedded in a class definition.\n\nThe first expression may also be a tuple of length 2 or 3.  In this\ncase, the optional parts must be omitted.  The form "exec(expr,\nglobals)" is equivalent to "exec expr in globals", while the form\n"exec(expr, globals, locals)" is equivalent to "exec expr in globals,\nlocals".  The tuple form of "exec" provides compatibility with Python\n3, where "exec" is a function rather than a statement.\n\nChanged in version 2.4: Formerly, *locals* was required to be a\ndictionary.\n\nAs a side effect, an implementation may insert additional keys into\nthe dictionaries given besides those corresponding to variable names\nset by the executed code.  For example, the current implementation may\nadd a reference to the dictionary of the built-in module "__builtin__"\nunder the key "__builtins__" (!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is supported\nby the built-in function "eval()".  The built-in functions "globals()"\nand "locals()" return the current global and local dictionary,\nrespectively, which may be useful to pass around for use by "exec".\n\n-[ Footnotes ]-\n\n[1] Note that the parser only accepts the Unix-style end of line\n    convention. If you are reading the code from a file, make sure to\n    use *universal newlines* mode to convert Windows or Mac-style\n    newlines.\n',
- 'execmodel': u'\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 file read by the\nbuilt-in function "execfile()" is a code block.  The string argument\npassed to the built-in function "eval()" and to the "exec" statement\nis a code block. The expression read and evaluated by the built-in\nfunction "input()" 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 generator expressions since\nthey are implemented using a function scope.  This means that the\nfollowing 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.\nIf a name is bound at the module level, it is a global variable.  (The\nvariables of the module code block are local and global.)  If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\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, in the\nsecond position of an "except" clause header or after "as" in a "with"\nstatement.  The "import" statement of the form "from ... import *"\nbinds all names defined in the imported module, except those beginning\nwith an underscore.  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 name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module "__builtin__".  The global namespace is searched first.\nIf the name is not found there, the builtins namespace is searched.\nThe global statement must precede all uses of the name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name "__builtins__" in its global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used).  By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "__builtin__" (note: no\n\'s\'); when in any other module, "__builtins__" is an alias for the\ndictionary of the "__builtin__" module itself.  "__builtins__" can be\nset to a user-created dictionary to create a weak form of restricted\nexecution.\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 "__builtin__" (no \'s\') module and modify its attributes\nappropriately.\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\nin the 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\nIf "exec" is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n"SyntaxError" unless the exec explicitly specifies the local namespace\nfor the "exec".  (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames.  Names may be resolved in the local and global namespaces of\nthe caller.  Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" 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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof.  The instance can be\nreceived by the handler and can carry additional information about the\nexceptional condition.\n\nExceptions can also be identified by strings, in which case the\n"except" clause is selected by object identity.  An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API.  Their\n  contents may change from one version of Python to the next without\n  warning and should not be relied on by code which will run under\n  multiple 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\n    these operations is not available at the time the module is\n    compiled.\n',
+ 'else': u'\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': u'\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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof.  The instance can be\nreceived by the handler and can carry additional information about the\nexceptional condition.\n\nExceptions can also be identified by strings, in which case the\n"except" clause is selected by object identity.  An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API.  Their\n  contents may change from one version of Python to the next without\n  warning and should not be relied on by code which will run under\n  multiple 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\n    these operations is not available at the time the module is\n    compiled.\n',
+ 'exec': u'\nThe "exec" statement\n********************\n\n   exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]\n\nThis statement supports dynamic execution of Python code.  The first\nexpression should evaluate to either a Unicode string, a *Latin-1*\nencoded string, an open file object, a code object, or a tuple.  If it\nis a string, the string is parsed as a suite of Python statements\nwhich is then executed (unless a syntax error occurs). [1] If it is an\nopen file, the file is parsed until EOF and executed. If it is a code\nobject, it is simply executed.  For the interpretation of a tuple, see\nbelow.  In all cases, the code that\'s executed is expected to be valid\nas file input (see section File input).  Be aware that the "return"\nand "yield" statements may not be used outside of function definitions\neven within the context of code passed to the "exec" statement.\n\nIn all cases, if the optional parts are omitted, the code is executed\nin the current scope.  If only the first expression after "in" is\nspecified, it should be a dictionary, which will be used for both the\nglobal and the local variables.  If two expressions are given, they\nare used for the global and local variables, respectively. If\nprovided, *locals* can be any mapping object. Remember that at module\nlevel, globals and locals are the same dictionary. If two separate\nobjects are given as *globals* and *locals*, the code will be executed\nas if it were embedded in a class definition.\n\nThe first expression may also be a tuple of length 2 or 3.  In this\ncase, the optional parts must be omitted.  The form "exec(expr,\nglobals)" is equivalent to "exec expr in globals", while the form\n"exec(expr, globals, locals)" is equivalent to "exec expr in globals,\nlocals".  The tuple form of "exec" provides compatibility with Python\n3, where "exec" is a function rather than a statement.\n\nChanged in version 2.4: Formerly, *locals* was required to be a\ndictionary.\n\nAs a side effect, an implementation may insert additional keys into\nthe dictionaries given besides those corresponding to variable names\nset by the executed code.  For example, the current implementation may\nadd a reference to the dictionary of the built-in module "__builtin__"\nunder the key "__builtins__" (!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is supported\nby the built-in function "eval()".  The built-in functions "globals()"\nand "locals()" return the current global and local dictionary,\nrespectively, which may be useful to pass around for use by "exec".\n\n-[ Footnotes ]-\n\n[1] Note that the parser only accepts the Unix-style end of line\n    convention. If you are reading the code from a file, make sure to\n    use *universal newlines* mode to convert Windows or Mac-style\n    newlines.\n',
+ 'execmodel': u'\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 file read by the\nbuilt-in function "execfile()" is a code block.  The string argument\npassed to the built-in function "eval()" and to the "exec" statement\nis a code block. The expression read and evaluated by the built-in\nfunction "input()" 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 generator expressions since\nthey are implemented using a function scope.  This means that the\nfollowing 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.\nIf a name is bound at the module level, it is a global variable.  (The\nvariables of the module code block are local and global.)  If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\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, in the\nsecond position of an "except" clause header or after "as" in a "with"\nstatement.  The "import" statement of the form "from ... import *"\nbinds all names defined in the imported module, except those beginning\nwith an underscore.  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 name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module "__builtin__".  The global namespace is searched first.\nIf the name is not found there, the builtins namespace is searched.\nThe global statement must precede all uses of the name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name "__builtins__" in its global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used).  By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "__builtin__" (note: no\n\'s\'); when in any other module, "__builtins__" is an alias for the\ndictionary of the "__builtin__" module itself.  "__builtins__" can be\nset to a user-created dictionary to create a weak form of restricted\nexecution.\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 "__builtin__" (no \'s\') module and modify its attributes\nappropriately.\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\nin the 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\nIf "exec" is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n"SyntaxError" unless the exec explicitly specifies the local namespace\nfor the "exec".  (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames.  Names may be resolved in the local and global namespaces of\nthe caller.  Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" 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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof.  The instance can be\nreceived by the handler and can carry additional information about the\nexceptional condition.\n\nExceptions can also be identified by strings, in which case the\n"except" clause is selected by object identity.  An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API.  Their\n  contents may change from one version of Python to the next without\n  warning and should not be relied on by code which will run under\n  multiple 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\n    these operations is not available at the time the module is\n    compiled.\n',
  'exprlists': u'\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': u'\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 of floating point numbers can\nlook like octal integers, but are interpreted using radix 10.  For\nexample, "077e010" is legal, and denotes the same number as "77e10".\nThe allowed range of floating point literals is implementation-\ndependent. 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': u'\nThe "for" statement\n*******************\n\nThe "for" statement is used to iterate over the elements of a sequence\n(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, and then the suite is executed.  When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there was no next\nitem.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop.  Hint: the built-in function "range()" returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s "for i := a to b\ndo"; e.g., "range(3)" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (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': u'\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"\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 is\npreceded by a colon "\':\'".  These specify a non-default format for the\nreplacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword.  If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument.  If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings "\'10\'" or\n"\':-]\'") within a format string. The *arg_name* can be followed by any\nnumber of index or attribute expressions. An expression of the form\n"\'.name\'" selects the named attribute using "getattr()", while an\nexpression of the form "\'[index]\'" does an index lookup using\n"__getitem__()".\n\nChanged in version 2.7: 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 "__format__()"\nmethod of the value itself.  However, in some cases it is desirable to\nforce a type to be formatted as a string, overriding its own\ndefinition of formatting.  By converting the value to a string before\ncalling "__format__()", the normal formatting logic is bypassed.\n\nTwo conversion flags are currently supported: "\'!s\'" which calls\n"str()" on the value, and "\'!r\'" which calls "repr()".\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\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-empty\nformat 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        ::= <any character>\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\nIf a valid *align* value is specified, it can be preceded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. Note that it is not possible to use "{" and "}" as *fill*\nchar while using the "str.format()" method; this limitation however\ndoesn\'t affect the "format()" function.\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 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\'", respectively.\n\nThe "\',\'" option signals the use of a comma for a thousands separator.\nFor a locale aware separator, use the "\'n\'" integer presentation type\ninstead.\n\nChanged in version 2.7: Added the "\',\'" option (see also **PEP 378**).\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\nPreceding the *width* field by a zero ("\'0\'") character enables sign-\naware zero-padding for numeric types.  This is equivalent to a *fill*\ncharacter of "\'0\'" with an *alignment* type of "\'=\'".\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 point\nfor a floating point value formatted with "\'g\'" or "\'G\'".  For non-\nnumber types the field indicates the maximum field size - in other\nwords, how many characters will be used from the field content. The\n*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 the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | 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\'"\nand None). When doing so, "float()" is used to convert the integer to\na 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   |           | The default precision is "6".                              |\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   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'F\'"     | Fixed point. Same as "\'f\'".                                |\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 "p-1" |\n   |           | would have exponent "exp".  Then if "-4 <= exp < p", the   |\n   |           | number is formatted with presentation type "\'f\'" and       |\n   |           | precision "p-1-exp".  Otherwise, the number is formatted   |\n   |           | with presentation type "\'e\'" and precision "p-1". In both  |\n   |           | cases insignificant trailing zeros are removed from the    |\n   |           | significand, and the decimal point is also removed if      |\n   |           | there are no remaining digits following it.  Positive and  |\n   |           | negative infinity, positive and negative zero, and nans,   |\n   |           | are formatted as "inf", "-inf", "0", "-0" and "nan"        |\n   |           | respectively, regardless of the precision.  A precision of |\n   |           | "0" is treated as equivalent to a precision of "1". The    |\n   |           | default precision is "6".                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'G\'"     | General format. Same as "\'g\'" except switches to "\'E\'" if  |\n   |           | the number gets too large. The representations of infinity |\n   |           | and NaN are uppercased, too.                               |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'g\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | 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      | The same as "\'g\'".                                         |\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 "%"-formatting,\nwith the addition of the "{}" and with ":" used instead of "%". For\nexample, "\'%03.2f\'" can be translated to "\'{: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\')  # 2.7+ 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(object):\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 bases:\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.5\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}\'.format(points/total)\n   \'Correct answers: 88.64%\'\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),\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': u'\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   decorated      ::= decorators (classdef | funcdef)\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   funcdef        ::= "def" funcname "(" [parameter_list] ")" ":" suite\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" identifier ["," "**" identifier]\n                      | "**" identifier\n                      | defparameter [","] )\n   defparameter   ::= parameter ["=" expression]\n   sublist        ::= parameter ("," parameter)* [","]\n   parameter      ::= identifier | "(" sublist ")"\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 top-level *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 must also have a default value --- this is a syntactic\nrestriction 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 the 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 any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements.\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',
+ 'formatstrings': u'\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"\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 is\npreceded by a colon "\':\'".  These specify a non-default format for the\nreplacement value.\n\nSee also the Format Specification Mini-Language section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword.  If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument.  If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings "\'10\'" or\n"\':-]\'") within a format string. The *arg_name* can be followed by any\nnumber of index or attribute expressions. An expression of the form\n"\'.name\'" selects the named attribute using "getattr()", while an\nexpression of the form "\'[index]\'" does an index lookup using\n"__getitem__()".\n\nChanged in version 2.7: 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 "__format__()"\nmethod of the value itself.  However, in some cases it is desirable to\nforce a type to be formatted as a string, overriding its own\ndefinition of formatting.  By converting the value to a string before\ncalling "__format__()", the normal formatting logic is bypassed.\n\nTwo conversion flags are currently supported: "\'!s\'" which calls\n"str()" on the value, and "\'!r\'" which calls "repr()".\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\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-empty\nformat 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        ::= <any character>\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\nIf a valid *align* value is specified, it can be preceded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. Note that it is not possible to use "{" and "}" as *fill*\nchar while using the "str.format()" method; this limitation however\ndoesn\'t affect the "format()" function.\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 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\'", respectively.\n\nThe "\',\'" option signals the use of a comma for a thousands separator.\nFor a locale aware separator, use the "\'n\'" integer presentation type\ninstead.\n\nChanged in version 2.7: Added the "\',\'" option (see also **PEP 378**).\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\nPreceding the *width* field by a zero ("\'0\'") character enables sign-\naware zero-padding for numeric types.  This is equivalent to a *fill*\ncharacter of "\'0\'" with an *alignment* type of "\'=\'".\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 point\nfor a floating point value formatted with "\'g\'" or "\'G\'".  For non-\nnumber types the field indicates the maximum field size - in other\nwords, how many characters will be used from the field content. The\n*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 the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | 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\'"\nand None). When doing so, "float()" is used to convert the integer to\na 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   |           | The default precision is "6".                              |\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   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'F\'"     | Fixed point. Same as "\'f\'".                                |\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 "p-1" |\n   |           | would have exponent "exp".  Then if "-4 <= exp < p", the   |\n   |           | number is formatted with presentation type "\'f\'" and       |\n   |           | precision "p-1-exp".  Otherwise, the number is formatted   |\n   |           | with presentation type "\'e\'" and precision "p-1". In both  |\n   |           | cases insignificant trailing zeros are removed from the    |\n   |           | significand, and the decimal point is also removed if      |\n   |           | there are no remaining digits following it.  Positive and  |\n   |           | negative infinity, positive and negative zero, and nans,   |\n   |           | are formatted as "inf", "-inf", "0", "-0" and "nan"        |\n   |           | respectively, regardless of the precision.  A precision of |\n   |           | "0" is treated as equivalent to a precision of "1". The    |\n   |           | default precision is "6".                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'G\'"     | General format. Same as "\'g\'" except switches to "\'E\'" if  |\n   |           | the number gets too large. The representations of infinity |\n   |           | and NaN are uppercased, too.                               |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'g\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | 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      | The same as "\'g\'".                                         |\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 "%"-formatting,\nwith the addition of the "{}" and with ":" used instead of "%". For\nexample, "\'%03.2f\'" can be translated to "\'{: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\')  # 2.7+ 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(object):\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 bases:\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.5\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}\'.format(points/total)\n   \'Correct answers: 88.64%\'\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),\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': u'\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection The standard type hierarchy):\n\n   decorated      ::= decorators (classdef | funcdef)\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   funcdef        ::= "def" funcname "(" [parameter_list] ")" ":" suite\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" identifier ["," "**" identifier]\n                      | "**" identifier\n                      | defparameter [","] )\n   defparameter   ::= parameter ["=" expression]\n   sublist        ::= parameter ("," parameter)* [","]\n   parameter      ::= identifier | "(" sublist ")"\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 top-level *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 must also have a default value --- this is a syntactic\nrestriction 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 the 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 Calls.\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values.  If the form ""*identifier"" is\npresent, it is initialized to a tuple receiving any excess positional\nparameters, defaulting to the empty tuple.  If the form\n""**identifier"" is present, it is initialized to a new dictionary\nreceiving any excess keyword arguments, defaulting to a new empty\ndictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section Lambdas.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements.\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': u'\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 code\nblock 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.  It\napplies only to code parsed at the same time as the "global"\nstatement. In particular, a "global" statement contained in an "exec"\nstatement does not affect the code block *containing* the "exec"\nstatement, and code contained in an "exec" statement is unaffected by\n"global" statements in the code containing the "exec" statement.  The\nsame applies to the "eval()", "execfile()" and "compile()" functions.\n',
- 'id-classes': u'\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 the\n   last evaluation; it is stored in the "__builtin__" 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 not\n   follow explicitly documented use, is subject to breakage without\n   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': u'\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions:\n\n   identifier ::= (letter|"_") (letter | digit | "_")*\n   letter     ::= lowercase | uppercase\n   lowercase  ::= "a"..."z"\n   uppercase  ::= "A"..."Z"\n   digit      ::= "0"..."9"\n\nIdentifiers are unlimited in length.  Case is significant.\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   and       del       from      not       while\n   as        elif      global    or        with\n   assert    else      if        pass      yield\n   break     except    import    print\n   class     exec      in        raise\n   continue  finally   is        return\n   def       for       lambda    try\n\nChanged in version 2.4: "None" became a constant and is now recognized\nby the compiler as a name for the built-in object "None".  Although it\nis not a keyword, you cannot assign a different object to it.\n\nChanged in version 2.5: Using "as" and "with" as identifiers triggers\na warning.  To use them as keywords, enable the "with_statement"\nfuture feature .\n\nChanged in version 2.6: "as" and "with" are full keywords.\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 the\n   last evaluation; it is stored in the "__builtin__" 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 not\n   follow explicitly documented use, is subject to breakage without\n   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': u'\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',
+ 'id-classes': u'\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 the\n   last evaluation; it is stored in the "__builtin__" 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 and\n   elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of "__*__" names, in any context, that does not\n   follow explicitly documented use, is subject to breakage without\n   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': u'\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions:\n\n   identifier ::= (letter|"_") (letter | digit | "_")*\n   letter     ::= lowercase | uppercase\n   lowercase  ::= "a"..."z"\n   uppercase  ::= "A"..."Z"\n   digit      ::= "0"..."9"\n\nIdentifiers are unlimited in length.  Case is significant.\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   and       del       from      not       while\n   as        elif      global    or        with\n   assert    else      if        pass      yield\n   break     except    import    print\n   class     exec      in        raise\n   continue  finally   is        return\n   def       for       lambda    try\n\nChanged in version 2.4: "None" became a constant and is now recognized\nby the compiler as a name for the built-in object "None".  Although it\nis not a keyword, you cannot assign a different object to it.\n\nChanged in version 2.5: Using "as" and "with" as identifiers triggers\na warning.  To use them as keywords, enable the "with_statement"\nfuture feature .\n\nChanged in version 2.6: "as" and "with" are full keywords.\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 the\n   last evaluation; it is stored in the "__builtin__" 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 and\n   elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of "__*__" names, in any context, that does not\n   follow explicitly documented use, is subject to breakage without\n   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': u'\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': u'\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': u'\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 each\nidentifier in the list. The form with "from" performs step (1) once,\nand then performs step (2) repeatedly.\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.\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.\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 **PEP\n302**). The object is a list of *finder* objects which are queried in\norder as to whether they know how to load the module by calling their\n"find_module()" method with the name of the module. If the module\nhappens to be contained within a package (as denoted by the existence\nof a dot in the name), then a second argument to "find_module()" is\ngiven as the value of the "__path__" attribute from the parent package\n(everything up to the last dot in the name of the module being\nimported). If a finder can find the module it returns a *loader*\n(discussed later) or returns "None".\n\nIf none of the finders on "sys.meta_path" are able to find the module\nthen some implicitly defined finders are queried. Implementations of\nPython vary in what implicit meta path finders are defined. The one\nthey all do define, though, is one that handles "sys.path_hooks",\n"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 for\na 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 a\nsingle 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, file-\nbased finder that handles modules stored as individual files should be\nused for that path. If the path does not exist then a finder which\nalways 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 the\nimport machinery) then it is to use that module for initialization and\nnot a new module. But if the module does not exist in "sys.modules"\nthen it is to be added to that dict before initialization begins. If\nan error occurs during loading of the module and it was added to\n"sys.modules" it is to be removed from the dict. If an error occurs\nbut the module was already in "sys.modules" it is left in the dict.\n\nThe loader must set several attributes on the module. "__name__" is to\nbe set to the name of the module. "__file__" is to be the "path" to\nthe file unless the module is built-in (and thus listed in\n"sys.builtin_module_names") in which case the attribute is not set. If\nwhat is being imported is a package then "__path__" is to be set to a\nlist of paths to be searched when looking for modules and packages\ncontained within the package being imported. "__package__" is optional\nbut should be set to the name of package that contains the module or\npackage (the empty string is used for module not contained in a\npackage). "__loader__" is also optional but should be set to the\nloader object that is loading the module.\n\nIf an error occurs during loading then the loader raises "ImportError"\nif some other exception is not already being propagated. Otherwise the\nloader returns the module that was loaded and 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", the\nname 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 are\nbound 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 must\nbe a sequence of strings which are names defined or imported by that\nmodule.  The names given in "__all__" are all considered public and\nare required to exist.  If "__all__" is not defined, the set of public\nnames includes all names found in the module\'s namespace which do not\nbegin with an underscore character ("\'_\'"). "__all__" should contain\nthe entire public API. It is intended to avoid accidentally exporting\nitems that are not part of the API (such as library modules which were\nimported and used within the module).\n\nThe "from" form with "*" may only occur in a module scope.  If the\nwild card form of import --- "import *" --- is used in a function and\nthe function contains or is a nested block with free variables, the\ncompiler will 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" you\ncan 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 will\nend up importing "pkg.mod". If you execute "from ..subpkg2 import mod"\nfrom within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\nspecification for relative imports is contained 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 2.6 are "unicode_literals",\n"print_function", "absolute_import", "division", "generators",\n"nested_scopes" and "with_statement".  "generators", "with_statement",\n"nested_scopes" are redundant in Python version 2.6 and above because\nthey are always enabled.\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 will\nbe 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 an "exec" statement or calls to the built-in\nfunctions "compile()" and "execfile()" that occur in a module "M"\ncontaining a future statement will, by default, use the new  syntax or\nsemantics associated with the future statement.  This can, starting\nwith Python 2.2 be controlled by optional arguments to "compile()" ---\nsee the documentation of that function for 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: **PEP 236** - Back to the __future__\n\n     The original proposal for the __future__ mechanism.\n',
- 'in': u'\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 only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound 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", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects need not have the same type. If both are\nnumbers, they are converted to a common type.  Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section *Special method names*.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n  equivalents (the result of the built-in function "ord()") of their\n  characters. Unicode and 8-bit strings are fully interoperable in\n  this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n  of 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, "cmp([1,2,x], [1,2,y])" returns\n  the same as "cmp(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 their sorted\n  (key, value) lists compare equal. [5] Outcomes other than equality\n  are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n  are the same object; the choice whether one object is considered\n  smaller or larger than another one is made arbitrarily but\n  consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership.  "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise.  "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object.  However, it make sense\nfor many other object types to support membership tests without being\na sequence.  In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*.  An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin 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 == z"\nis produced while iterating over "y".  If an exception is raised\nduring 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 y" is\ntrue if and only if *x* and *y* are the same object.  "x is not y"\nyields the inverse truth value. [7]\n',
+ 'import': u'\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 each\nidentifier in the list. The form with "from" performs step (1) once,\nand then performs step (2) repeatedly.\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.\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.\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 **PEP\n302**). The object is a list of *finder* objects which are queried in\norder as to whether they know how to load the module by calling their\n"find_module()" method with the name of the module. If the module\nhappens to be contained within a package (as denoted by the existence\nof a dot in the name), then a second argument to "find_module()" is\ngiven as the value of the "__path__" attribute from the parent package\n(everything up to the last dot in the name of the module being\nimported). If a finder can find the module it returns a *loader*\n(discussed later) or returns "None".\n\nIf none of the finders on "sys.meta_path" are able to find the module\nthen some implicitly defined finders are queried. Implementations of\nPython vary in what implicit meta path finders are defined. The one\nthey all do define, though, is one that handles "sys.path_hooks",\n"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 for\na 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 a\nsingle 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, file-\nbased finder that handles modules stored as individual files should be\nused for that path. If the path does not exist then a finder which\nalways 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 the\nimport machinery) then it is to use that module for initialization and\nnot a new module. But if the module does not exist in "sys.modules"\nthen it is to be added to that dict before initialization begins. If\nan error occurs during loading of the module and it was added to\n"sys.modules" it is to be removed from the dict. If an error occurs\nbut the module was already in "sys.modules" it is left in the dict.\n\nThe loader must set several attributes on the module. "__name__" is to\nbe set to the name of the module. "__file__" is to be the "path" to\nthe file unless the module is built-in (and thus listed in\n"sys.builtin_module_names") in which case the attribute is not set. If\nwhat is being imported is a package then "__path__" is to be set to a\nlist of paths to be searched when looking for modules and packages\ncontained within the package being imported. "__package__" is optional\nbut should be set to the name of package that contains the module or\npackage (the empty string is used for module not contained in a\npackage). "__loader__" is also optional but should be set to the\nloader object that is loading the module.\n\nIf an error occurs during loading then the loader raises "ImportError"\nif some other exception is not already being propagated. Otherwise the\nloader returns the module that was loaded and 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", the\nname 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 are\nbound 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 must\nbe a sequence of strings which are names defined or imported by that\nmodule.  The names given in "__all__" are all considered public and\nare required to exist.  If "__all__" is not defined, the set of public\nnames includes all names found in the module\'s namespace which do not\nbegin with an underscore character ("\'_\'"). "__all__" should contain\nthe entire public API. It is intended to avoid accidentally exporting\nitems that are not part of the API (such as library modules which were\nimported and used within the module).\n\nThe "from" form with "*" may only occur in a module scope.  If the\nwild card form of import --- "import *" --- is used in a function and\nthe function contains or is a nested block with free variables, the\ncompiler will 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" you\ncan 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 will\nend up importing "pkg.mod". If you execute "from ..subpkg2 import mod"\nfrom within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\nspecification for relative imports is contained 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 2.6 are "unicode_literals",\n"print_function", "absolute_import", "division", "generators",\n"nested_scopes" and "with_statement".  "generators", "with_statement",\n"nested_scopes" are redundant in Python version 2.6 and above because\nthey are always enabled.\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 will\nbe 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 an "exec" statement or calls to the built-in\nfunctions "compile()" and "execfile()" that occur in a module "M"\ncontaining a future statement will, by default, use the new  syntax or\nsemantics associated with the future statement.  This can, starting\nwith Python 2.2 be controlled by optional arguments to "compile()" ---\nsee the documentation of that function for 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: **PEP 236** - Back to the __future__\n\n     The original proposal for the __future__ mechanism.\n',
+ 'in': u'\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 only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound 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", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects need not have the same type. If both are\nnumbers, they are converted to a common type.  Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section Special method names.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n  equivalents (the result of the built-in function "ord()") of their\n  characters. Unicode and 8-bit strings are fully interoperable in\n  this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n  of 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, "cmp([1,2,x], [1,2,y])" returns\n  the same as "cmp(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 their sorted\n  (key, value) lists compare equal. [5] Outcomes other than equality\n  are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n  are the same object; the choice whether one object is considered\n  smaller or larger than another one is made arbitrarily but\n  consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership.  "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise.  "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object.  However, it make sense\nfor many other object types to support membership tests without being\na sequence.  In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*.  An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin 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 == z"\nis produced while iterating over "y".  If an exception is raised\nduring 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 y" is\ntrue if and only if *x* and *y* are the same object.  "x is not y"\nyields the inverse truth value. [7]\n',
  'integers': u'\nInteger and long integer literals\n*********************************\n\nInteger and long integer literals are described by the following\nlexical definitions:\n\n   longinteger    ::= integer ("l" | "L")\n   integer        ::= decimalinteger | octinteger | hexinteger | bininteger\n   decimalinteger ::= nonzerodigit digit* | "0"\n   octinteger     ::= "0" ("o" | "O") octdigit+ | "0" octdigit+\n   hexinteger     ::= "0" ("x" | "X") hexdigit+\n   bininteger     ::= "0" ("b" | "B") bindigit+\n   nonzerodigit   ::= "1"..."9"\n   octdigit       ::= "0"..."7"\n   bindigit       ::= "0" | "1"\n   hexdigit       ::= digit | "a"..."f" | "A"..."F"\n\nAlthough both lower case "\'l\'" and upper case "\'L\'" are allowed as\nsuffix for long integers, it is strongly recommended to always use\n"\'L\'", since the letter "\'l\'" looks too much like the digit "\'1\'".\n\nPlain integer literals that are above the largest representable plain\ninteger (e.g., 2147483647 when using 32-bit arithmetic) are accepted\nas if they were long integers instead. [1]  There is no limit for long\ninteger literals apart from what can be stored in available memory.\n\nSome examples of plain integer literals (first row) and long integer\nliterals (second and third rows):\n\n   7     2147483647                        0177\n   3L    79228162514264337593543950336L    0377L   0x100000000L\n         79228162514264337593543950336             0xdeadbeef\n',
- 'lambda': u'\nLambdas\n*******\n\n   lambda_expr     ::= "lambda" [parameter_list]: expression\n   old_lambda_expr ::= "lambda" [parameter_list]: old_expression\n\nLambda expressions (sometimes called lambda forms) have the same\nsyntactic position as expressions.  They are a shorthand to create\nanonymous functions; the expression "lambda arguments: expression"\nyields a function object.  The unnamed object behaves like a function\nobject defined with\n\n   def name(arguments):\n       return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda expressions cannot contain\nstatements.\n',
+ 'lambda': u'\nLambdas\n*******\n\n   lambda_expr     ::= "lambda" [parameter_list]: expression\n   old_lambda_expr ::= "lambda" [parameter_list]: old_expression\n\nLambda expressions (sometimes called lambda forms) have the same\nsyntactic position as expressions.  They are a shorthand to create\nanonymous functions; the expression "lambda arguments: expression"\nyields a function object.  The unnamed object behaves like a function\nobject defined with\n\n   def name(arguments):\n       return expression\n\nSee section Function definitions for the syntax of parameter lists.\nNote that functions created with lambda expressions cannot contain\nstatements.\n',
  'lists': u'\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n   list_display        ::= "[" [expression_list | list_comprehension] "]"\n   list_comprehension  ::= expression list_for\n   list_for            ::= "for" target_list "in" old_expression_list [list_iter]\n   old_expression_list ::= old_expression [("," old_expression)+ [","]]\n   old_expression      ::= or_test | old_lambda_expr\n   list_iter           ::= list_for | list_if\n   list_if             ::= "if" old_expression [list_iter]\n\nA list display yields a new list object.  Its contents are specified\nby providing either a list of expressions or a list comprehension.\nWhen a comma-separated list of expressions is supplied, its elements\nare evaluated from left to right and placed into the list object in\nthat order.  When a list comprehension is supplied, it consists of a\nsingle expression followed by at least one "for" clause and zero or\nmore "for" or "if" clauses.  In this case, the elements of the new\nlist are those that would be produced by considering each of the "for"\nor "if" clauses a block, nesting from left to right, and evaluating\nthe expression to produce a list element each time the innermost block\nis reached [1].\n',
  'naming': u'\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 file read by the\nbuilt-in function "execfile()" is a code block.  The string argument\npassed to the built-in function "eval()" and to the "exec" statement\nis a code block. The expression read and evaluated by the built-in\nfunction "input()" 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 generator expressions since\nthey are implemented using a function scope.  This means that the\nfollowing 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.\nIf a name is bound at the module level, it is a global variable.  (The\nvariables of the module code block are local and global.)  If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\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, in the\nsecond position of an "except" clause header or after "as" in a "with"\nstatement.  The "import" statement of the form "from ... import *"\nbinds all names defined in the imported module, except those beginning\nwith an underscore.  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 name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module "__builtin__".  The global namespace is searched first.\nIf the name is not found there, the builtins namespace is searched.\nThe global statement must precede all uses of the name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name "__builtins__" in its global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used).  By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "__builtin__" (note: no\n\'s\'); when in any other module, "__builtins__" is an alias for the\ndictionary of the "__builtin__" module itself.  "__builtins__" can be\nset to a user-created dictionary to create a weak form of restricted\nexecution.\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 "__builtin__" (no \'s\') module and modify its attributes\nappropriately.\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\nin the 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\nIf "exec" is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n"SyntaxError" unless the exec explicitly specifies the local namespace\nfor the "exec".  (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames.  Names may be resolved in the local and global namespaces of\nthe caller.  Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
  'numbers': u'\nNumeric literals\n****************\n\nThere are four types of numeric literals: plain integers, long\nintegers, floating point numbers, and imaginary numbers.  There are no\ncomplex literals (complex numbers can be formed by adding a real\nnumber and an imaginary 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 the\nliteral "1".\n',
  'numeric-types': u'\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.__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 ("+", "-", "*", "//", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|").  For instance, to evaluate the\n   expression "x + y", where *x* is an instance of a class that has an\n   "__add__()" method, "x.__add__(y)" is called.  The "__divmod__()"\n   method should be the equivalent to using "__floordiv__()" and\n   "__mod__()"; it should not be related to "__truediv__()" (described\n   below).  Note that "__pow__()" should be defined to accept an\n   optional third argument if the ternary version of the built-in\n   "pow()" function 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.__div__(self, other)\nobject.__truediv__(self, other)\n\n   The division operator ("/") is implemented by these methods.  The\n   "__truediv__()" method is used when "__future__.division" is in\n   effect, otherwise "__div__()" is used.  If only one of these two\n   methods is defined, the object will not support division in the\n   alternate context; "TypeError" will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(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 ("+", "-", "*", "/", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|") with reflected (swapped) operands.\n   These functions are only called if the left operand does not\n   support the corresponding operation and the operands are of\n   different types. [2] For instance, to evaluate the expression "x -\n   y", where *y* is an instance of a class that has an "__rsub__()"\n   method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n   *NotImplemented*.\n\n   Note that ternary "pow()" will not try calling "__rpow__()" (the\n   coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left\n     operand\'s type and that subclass provides the reflected method\n     for the operation, this method will be called before the left\n     operand\'s non-reflected method.  This behavior allows subclasses\n     to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(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 should attempt to do the\n   operation in-place (modifying *self*) and return the result (which\n   could be, but does not have to be, *self*).  If a specific method\n   is not defined, the augmented assignment falls back to the normal\n   methods.  For instance, to execute the statement "x += y", where\n   *x* is an instance of a class that has an "__iadd__()" method,\n   "x.__iadd__(y)" is called.  If *x* is an instance of a class that\n   does not define a "__iadd__()" method, "x.__add__(y)" and\n   "y.__radd__(x)" are 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.__long__(self)\nobject.__float__(self)\n\n   Called to implement the built-in functions "complex()", "int()",\n   "long()", and "float()".  Should return a value of the appropriate\n   type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n   Called to implement the built-in functions "oct()" and "hex()".\n   Should return a string value.\n\nobject.__index__(self)\n\n   Called to implement "operator.index()".  Also called whenever\n   Python needs an integer object (such as in slicing).  Must return\n   an integer (int or long).\n\n   New in version 2.5.\n\nobject.__coerce__(self, other)\n\n   Called to implement "mixed-mode" numeric arithmetic.  Should either\n   return a 2-tuple containing *self* and *other* converted to a\n   common numeric type, or "None" if conversion is impossible.  When\n   the common type would be the type of "other", it is sufficient to\n   return "None", since the interpreter will also ask the other object\n   to attempt a coercion (but sometimes, if the implementation of the\n   other type cannot be changed, it is useful to do the conversion to\n   the other type here).  A return value of "NotImplemented" is\n   equivalent to returning "None".\n',
  'objects': u'\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. Do not depend\non immediate finalization of objects when they become unreachable (ex:\nalways close files).\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 provides a convenient way 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 = 1",\n"a" and "b" may or may not refer to the same object with the value\none, depending on the implementation, but after "c = []; d = []", "c"\nand "d" are guaranteed to refer to two different, unique, newly\ncreated empty lists. (Note that "c = d = []" assigns the same object\nto both "c" and "d".)\n',
- 'operator-summary': u'\nOperator precedence\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|                                                 | [8]                                   |\n+-------------------------------------------------+---------------------------------------+\n| "+x", "-x", "~x"                                | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| "**"                                            | Exponentiation [9]                    |\n+-------------------------------------------------+---------------------------------------+\n| "x[index]", "x[index:index]",                   | Subscription, slicing, call,          |\n| "x(arguments...)", "x.attribute"                | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| "(expressions...)", "[expressions...]", "{key:  | Binding or tuple display, list        |\n| value...}", "`expressions...`"                  | display, dictionary display, string   |\n|                                                 | conversion                            |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension "leaks"\n    the control variables of each "for" it contains into the\n    containing scope.  However, this behavior is deprecated, and\n    relying on it will not work in Python 3.\n\n[2] While "abs(x%y) < abs(y)" is true mathematically, for floats\n    it 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", which\n    is numerically exactly equal to "1e100".  The function\n    "math.fmod()" returns a result whose sign matches the sign of the\n    first argument instead, and so returns "-1e-100" in this case.\n    Which approach is more appropriate depends on the application.\n\n[3] If x is very close to an exact integer multiple of y, it\'s\n    possible for "floor(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 close\n    to "x".\n\n[4] While comparisons between unicode strings make sense at the\n    byte level, they may be counter-intuitive to users. For example,\n    the strings "u"\\u00C7"" and "u"\\u0043\\u0327"" compare differently,\n    even 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[5] The implementation computes this efficiently, without\n    constructing lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of\n    the sorted (key, value) lists, but this was very expensive for the\n    common case of comparing for equality.  An even earlier version of\n    Python compared dictionaries by identity only, but this caused\n    surprises because people expected to be able to test a dictionary\n    for emptiness by comparing it to "{}".\n\n[7] Due to automatic garbage-collection, free lists, and the\n    dynamic nature of descriptors, you may notice seemingly unusual\n    behaviour in certain uses of the "is" operator, like those\n    involving comparisons between instance methods, or constants.\n    Check their documentation for more info.\n\n[8] The "%" operator is also used for string formatting; the same\n    precedence applies.\n\n[9] The power operator "**" binds less tightly than an arithmetic\n    or bitwise unary operator on its right, that is, "2**-1" is "0.5".\n',
+ 'operator-summary': u'\nOperator precedence\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 from\nright 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|                                                 | [8]                                   |\n+-------------------------------------------------+---------------------------------------+\n| "+x", "-x", "~x"                                | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| "**"                                            | Exponentiation [9]                    |\n+-------------------------------------------------+---------------------------------------+\n| "x[index]", "x[index:index]",                   | Subscription, slicing, call,          |\n| "x(arguments...)", "x.attribute"                | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| "(expressions...)", "[expressions...]", "{key:  | Binding or tuple display, list        |\n| value...}", "`expressions...`"                  | display, dictionary display, string   |\n|                                                 | conversion                            |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension "leaks"\n    the control variables of each "for" it contains into the\n    containing scope.  However, this behavior is deprecated, and\n    relying on it will not work in Python 3.\n\n[2] While "abs(x%y) < abs(y)" is true mathematically, for floats\n    it 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", which\n    is numerically exactly equal to "1e100".  The function\n    "math.fmod()" returns a result whose sign matches the sign of the\n    first argument instead, and so returns "-1e-100" in this case.\n    Which approach is more appropriate depends on the application.\n\n[3] If x is very close to an exact integer multiple of y, it\'s\n    possible for "floor(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 close\n    to "x".\n\n[4] While comparisons between unicode strings make sense at the\n    byte level, they may be counter-intuitive to users. For example,\n    the strings "u"\\u00C7"" and "u"\\u0043\\u0327"" compare differently,\n    even 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[5] The implementation computes this efficiently, without\n    constructing lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of\n    the sorted (key, value) lists, but this was very expensive for the\n    common case of comparing for equality.  An even earlier version of\n    Python compared dictionaries by identity only, but this caused\n    surprises because people expected to be able to test a dictionary\n    for emptiness by comparing it to "{}".\n\n[7] Due to automatic garbage-collection, free lists, and the\n    dynamic nature of descriptors, you may notice seemingly unusual\n    behaviour in certain uses of the "is" operator, like those\n    involving comparisons between instance methods, or constants.\n    Check their documentation for more info.\n\n[8] The "%" operator is also used for string formatting; the same\n    precedence applies.\n\n[9] The power operator "**" binds less tightly than an arithmetic\n    or bitwise unary operator on its right, that is, "2**-1" is "0.5".\n',
  'pass': u'\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': u'\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.  The result type is that of the\narguments after coercion.\n\nWith mixed operand types, the coercion rules for binary arithmetic\noperators apply. For int and long int operands, the result has the\nsame type as the operands (after coercion) unless the second argument\nis negative; in that case, all arguments are converted to float and a\nfloat result is delivered. For example, "10**2" returns "100", but\n"10**-2" returns "0.01". (This last feature was added in Python 2.2.\nIn Python 2.1 and before, if both arguments were of integer types and\nthe second argument was negative, an exception was raised).\n\nRaising "0.0" to a negative power results in a "ZeroDivisionError".\nRaising a negative number to a fractional power results in a\n"ValueError".\n',
  'print': u'\nThe "print" statement\n*********************\n\n   print_stmt ::= "print" ([expression ("," expression)* [","]]\n                  | ">>" expression [("," expression)+ [","]])\n\n"print" evaluates each expression in turn and writes the resulting\nobject to standard output (see below).  If an object is not a string,\nit is first converted to a string using the rules for string\nconversions.  The (resulting or original) string is then written.  A\nspace is written before each object is (converted and) written, unless\nthe output system believes it is positioned at the beginning of a\nline.  This is the case (1) when no characters have yet been written\nto standard output, (2) when the last character written to standard\noutput is a whitespace character except "\' \'", or (3) when the last\nwrite operation on standard output was not a "print" statement. (In\nsome cases it may be functional to write an empty string to standard\noutput for this reason.)\n\nNote: Objects which act like file objects but which are not the\n  built-in file objects often do not properly emulate this aspect of\n  the file object\'s behavior, so it is best not to rely on this.\n\nA "\'\\n\'" character is written at the end, unless the "print" statement\nends with a comma.  This is the only action if the statement contains\njust the keyword "print".\n\nStandard output is defined as the file object named "stdout" in the\nbuilt-in module "sys".  If no such object exists, or if it does not\nhave a "write()" method, a "RuntimeError" exception is raised.\n\n"print" also has an extended form, defined by the second portion of\nthe syntax described above. This form is sometimes referred to as\n""print" chevron." In this form, the first expression after the ">>"\nmust evaluate to a "file-like" object, specifically an object that has\na "write()" method as described above.  With this extended form, the\nsubsequent expressions are printed to this file object.  If the first\nexpression evaluates to "None", then "sys.stdout" is used as the file\nfor output.\n',
- 'raise': u'\nThe "raise" statement\n*********************\n\n   raise_stmt ::= "raise" [expression ["," expression ["," 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 is\nraised instead).\n\nOtherwise, "raise" evaluates the expressions to get three objects,\nusing "None" as the value of omitted expressions.  The first two\nobjects are used to determine the *type* and *value* of the exception.\n\nIf the first object is an instance, the type of the exception is the\nclass of the instance, the instance itself is the value, and the\nsecond object must be "None".\n\nIf the first object is a class, it becomes the type of the exception.\nThe second object is used to determine the exception value: If it is\nan instance of the class, the instance becomes the exception value. If\nthe second object is a tuple, it is used as the argument list for the\nclass constructor; if it is "None", an empty argument list is used,\nand any other object is treated as a single argument to the\nconstructor.  The instance so created by calling the constructor is\nused as the exception value.\n\nIf a third object is present and not "None", it must be a traceback\nobject (see section *The standard type hierarchy*), and it is\nsubstituted instead of the current location as the place where the\nexception occurred.  If the third object is present and not a\ntraceback object or "None", a "TypeError" exception is raised.  The\nthree-expression form of "raise" is useful to re-raise an exception\ntransparently in an except clause, but "raise" with no expressions\nshould be preferred if the exception to be re-raised was the most\nrecently active exception in the current scope.\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',
+ 'raise': u'\nThe "raise" statement\n*********************\n\n   raise_stmt ::= "raise" [expression ["," expression ["," 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 is\nraised instead).\n\nOtherwise, "raise" evaluates the expressions to get three objects,\nusing "None" as the value of omitted expressions.  The first two\nobjects are used to determine the *type* and *value* of the exception.\n\nIf the first object is an instance, the type of the exception is the\nclass of the instance, the instance itself is the value, and the\nsecond object must be "None".\n\nIf the first object is a class, it becomes the type of the exception.\nThe second object is used to determine the exception value: If it is\nan instance of the class, the instance becomes the exception value. If\nthe second object is a tuple, it is used as the argument list for the\nclass constructor; if it is "None", an empty argument list is used,\nand any other object is treated as a single argument to the\nconstructor.  The instance so created by calling the constructor is\nused as the exception value.\n\nIf a third object is present and not "None", it must be a traceback\nobject (see section The standard type hierarchy), and it is\nsubstituted instead of the current location as the place where the\nexception occurred.  If the third object is present and not a\ntraceback object or "None", a "TypeError" exception is raised.  The\nthree-expression form of "raise" is useful to re-raise an exception\ntransparently in an except clause, but "raise" with no expressions\nshould be preferred if the exception to be re-raised was the most\nrecently active exception in the current scope.\n\nAdditional information on exceptions can be found in section\nExceptions, and information about handling exceptions is in section\nThe try statement.\n',
  'return': u'\nThe "return" statement\n**********************\n\n   return_stmt ::= "return" [expression_list]\n\n"return" may only occur syntactically nested in a function definition,\nnot within a nested class definition.\n\nIf an expression list is present, it is evaluated, else "None" is\nsubstituted.\n\n"return" leaves the current function call with the expression list (or\n"None") as return value.\n\nWhen "return" passes control out of a "try" statement with a "finally"\nclause, that "finally" clause is executed before really leaving the\nfunction.\n\nIn a generator function, the "return" statement is not allowed to\ninclude an "expression_list".  In that context, a bare "return"\nindicates that the generator is done and will cause "StopIteration" to\nbe raised.\n',
- 'sequence-types': u'\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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects.  The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects.  Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__coerce__()" or other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values.  It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n   doesn\'t define a "__nonzero__()" method and whose "__len__()"\n   method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" 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__()" 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 "iterkeys()".\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 "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\n   New in version 2.6.\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 test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see *this section in the\n   language reference*.\n',
+ 'sequence-types': u'\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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects.  The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects.  Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__coerce__()" or other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values.  It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n   doesn\'t define a "__nonzero__()" method and whose "__len__()"\n   method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" 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.__missing__(self, key)\n\n   Called by "dict"."__getitem__()" to implement "self[key]" for dict\n   subclasses when key is not in the dictionary.\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__()" 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 "iterkeys()".\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 "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\n   New in version 2.6.\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 test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see this section in the\n   language reference.\n',
  'shifting': u'\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 plain or long integers as arguments.  The\narguments are converted to a common type.  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)".\nNegative shift counts raise a "ValueError" exception.\n\nNote: In the current implementation, the right-hand operand is\n  required to be at most "sys.maxsize".  If the right-hand operand is\n  larger than "sys.maxsize" an "OverflowError" exception is raised.\n',
- 'slicings': u'\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 slicing:\n\n   slicing          ::= simple_slicing | extended_slicing\n   simple_slicing   ::= primary "[" short_slice "]"\n   extended_slicing ::= primary "[" slice_list "]"\n   slice_list       ::= slice_item ("," slice_item)* [","]\n   slice_item       ::= expression | proper_slice | ellipsis\n   proper_slice     ::= short_slice | long_slice\n   short_slice      ::= [lower_bound] ":" [upper_bound]\n   long_slice       ::= short_slice ":" [stride]\n   lower_bound      ::= expression\n   upper_bound      ::= expression\n   stride           ::= expression\n   ellipsis         ::= "..."\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 nor ellipses).  Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\n\nThe semantics for a simple slicing are as follows.  The primary must\nevaluate to a sequence object.  The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n"sys.maxint", respectively.  If either bound is negative, the\nsequence\'s length is added to it.  The slicing now selects all items\nwith index *k* such that "i <= k < j" where *i* and *j* are the\nspecified lower and upper bounds.  This may be an empty sequence.  It\nis not an error if *i* or *j* lie outside the range of valid indexes\n(such items don\'t exist so they aren\'t selected).\n\nThe semantics for an extended slicing are as follows.  The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed 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 an ellipsis slice\nitem is the built-in "Ellipsis" object.  The conversion of a proper\nslice is a slice object (see section *The standard type hierarchy*)\nwhose "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': u'\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\nobject.__methods__\n\n   Deprecated since version 2.2: Use the built-in function "dir()" to\n   get a list of an object\'s attributes. This attribute is no longer\n   available.\n\nobject.__members__\n\n   Deprecated since version 2.2: Use the built-in function "dir()" to\n   get a list of an object\'s attributes. This attribute is no longer\n   available.\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\n    in 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] Cased characters are those with general category property\n    being one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase),\n    or "Lt" (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a\n    singleton tuple whose only element is the tuple to be formatted.\n\n[6] The advantage of leaving the newline on is that returning an\n    empty string is then an unambiguous EOF indication.  It is also\n    possible (in cases where it might matter, for example, if you want\n    to make an exact copy of a file while scanning its lines) to tell\n    whether the last line of a file ended in a newline or not (yes\n    this happens!).\n',
- 'specialnames': u'\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 class,\nthen "x[i]" is roughly equivalent to "x.__getitem__(i)" for old-style\nclasses and "type(x).__getitem__(x, i)" for new-style classes.  Except\nwhere mentioned, attempts to execute an operation raise an exception\nwhen no appropriate method is defined (typically "AttributeError" or\n"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 an\n   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, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".  As a special constraint on\n   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, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__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 is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_traceback" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     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.exc_traceback" or "sys.last_traceback".  Circular references\n     which are garbage are detected when the option cycle detector is\n     enabled (it\'s on by default), but can only be cleaned up if there\n     are no Python-level "__del__()" methods involved. Refer to the\n     documentation 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\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python 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\n   See also the *-R* command-line option.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function and by string conversions\n   (reverse quotes) to compute the "official" string representation of\n   an object.  If at all possible, this should look like a valid\n   Python expression that could be used to recreate an object with the\n   same value (given an appropriate environment).  If this is not\n   possible, a string of the form "<...some useful description...>"\n   should be returned.  The return value must be a string object. If a\n   class defines "__repr__()" but not "__str__()", then "__repr__()"\n   is also used when an "informal" string representation of instances\n   of that class is 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   statement to compute the "informal" string representation of an\n   object.  This differs from "__repr__()" in that it does not have to\n   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.__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   New in version 2.1.\n\n   These are the so-called "rich comparison" methods, and are called\n   for comparison operators in preference to "__cmp__()" below. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call "x.__ne__(y)",\n   "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result 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 the\n   paragraph on "__hash__()" for some important notes on creating\n   *hashable* objects which support custom comparison operations and\n   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 other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own 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.__cmp__(self, other)\n\n   Called by comparison operations if rich comparison (see above) is\n   not defined.  Should return a negative integer if "self < other",\n   zero if "self == other", a positive integer if "self > other".  If\n   no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n   class instances are compared by object identity ("address").  See\n   also the description of "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys. (Note: the\n   restriction that exceptions are not propagated by "__cmp__()" has\n   been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n   Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   If a class does not define a "__cmp__()" or "__eq__()" method it\n   should not define a "__hash__()" operation either; if it defines\n   "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n   not be usable in hashed collections.  If a class defines mutable\n   objects and implements a "__cmp__()" or "__eq__()" method, it\n   should not implement "__hash__()", since hashable collection\n   implementations require that a object\'s hash value is immutable (if\n   the object\'s hash value changes, it will be in the wrong hash\n   bucket).\n\n   User-defined classes have "__cmp__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns a result derived from\n   "id(x)".\n\n   Classes which inherit a "__hash__()" method from a parent class but\n   change the meaning of "__cmp__()" or "__eq__()" such that the hash\n   value returned is no longer appropriate (e.g. by switching to a\n   value-based concept of equality instead of the default identity\n   based equality) can explicitly flag themselves as being unhashable\n   by setting "__hash__ = None" in the class definition. Doing so\n   means that not only will instances of the class raise an\n   appropriate "TypeError" when a program attempts to retrieve their\n   hash value, but they will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)"\n   (unlike classes which define their own "__hash__()" to explicitly\n   raise "TypeError").\n\n   Changed in version 2.5: "__hash__()" may now also return a long\n   integer object; the 32-bit integer is then derived from the hash of\n   that object.\n\n   Changed in version 2.6: "__hash__" may now be set to "None" to\n   explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True", or their integer\n   equivalents "0" or "1".  When this method is not defined,\n   "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero. If a class defines\n   neither "__len__()" nor "__nonzero__()", all its instances are\n   considered true.\n\nobject.__unicode__(self)\n\n   Called to implement "unicode()" built-in; should return a Unicode\n   object. When this method is not defined, string conversion is\n   attempted, and the result of string conversion is converted to\n   Unicode using the system default encoding.\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") for\nclass 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. This\n   method should return the (computed) attribute value or raise an\n   "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 for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   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 in new-style classes.\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 not simply execute "self.name = value" --- this would cause\n   a recursive call to itself.  Instead, it should insert the value in\n   the dictionary of instance attributes, e.g., "self.__dict__[name] =\n   value".  For new-style classes, rather than accessing the instance\n   dictionary, it should call the base class method with the same\n   name, for example, "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\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See *Special method lookup for new-style\n     classes*.\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 an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  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 "AttributeError"\n   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, it\nis 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.  Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe 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 a new-style object instance, "a.x" is transformed\n   into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a new-style class, "A.x" is transformed into the\n   call: "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 "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\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__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented 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 both old and new-style classes have a\ndictionary for attribute storage.  This wastes space for objects\nhaving very few instance variables.  The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition.  The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable.  Space is saved because *__dict__* is\nnot created for each instance.\n\n__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   new-style class, *__slots__* reserves space for the declared\n   variables and prevents the automatic creation of *__dict__* and\n   *__weakref__* for each instance.\n\n   New in version 2.2.\n\nNotes on using *__slots__*\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  Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n  *__slots__* declaration would not enable the assignment of new\n  attributes not specifically listed in the sequence of instance\n  variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n  Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n  *__slots__* declaration would not enable support for weak\n  references.\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\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This 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 "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may 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  Changed in version 2.6: Previously, *__class__* assignment raised an\n  error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style 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 *__metaclass__* is defined then\nthe callable assigned to it will be called instead of "type()". 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\n  the 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\n__metaclass__\n\n   This variable can be any callable accepting arguments for "name",\n   "bases", and "dict".  Upon class creation, the callable is used\n   instead of the built-in "type()".\n\n   New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If "dict[\'__metaclass__\']" exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used (this looks for a *__class__* attribute first and if not found,\n  uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n  used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n  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\n\nCustomizing instance and subclass checks\n========================================\n\nNew in version 2.6.\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 in\norder 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: **PEP 3119** - Introducing Abstract Base Classes\n\n     Includes the specification for customizing "isinstance()" and\n     "issubclass()" behavior through "__instancecheck__()" and\n     "__subclasscheck__()", with motivation for this functionality in\n     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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects.  The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects.  Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__coerce__()" or other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values.  It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n   doesn\'t define a "__nonzero__()" method and whose "__len__()"\n   method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" 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__()" 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 "iterkeys()".\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 "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\n   New in version 2.6.\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 test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see *this section in the\n   language reference*.\n\n\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects.  Immutable sequences methods should at most only\ndefine "__getslice__()"; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n   Deprecated since version 2.0: Support slice objects as parameters\n   to the "__getitem__()" method. (However, built-in types in CPython\n   currently still implement "__getslice__()".  Therefore, you have to\n   override it in derived classes when implementing slicing.)\n\n   Called to implement evaluation of "self[i:j]". The returned object\n   should be of the same type as *self*.  Note that missing *i* or *j*\n   in the slice expression are replaced by zero or "sys.maxint",\n   respectively.  If negative indexes are used in the slice, the\n   length of the sequence is added to that index. If the instance does\n   not implement the "__len__()" method, an "AttributeError" is\n   raised. No guarantee is made that indexes adjusted this way are not\n   still negative.  Indexes which are greater than the length of the\n   sequence are not modified. If no "__getslice__()" is found, a slice\n   object is created instead, and passed to "__getitem__()" instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n   Called to implement assignment to "self[i:j]". Same notes for *i*\n   and *j* as for "__getslice__()".\n\n   This method is deprecated. If no "__setslice__()" is found, or for\n   extended slicing of the form "self[i:j:k]", a slice object is\n   created, and passed to "__setitem__()", instead of "__setslice__()"\n   being called.\n\nobject.__delslice__(self, i, j)\n\n   Called to implement deletion of "self[i:j]". Same notes for *i* and\n   *j* as for "__getslice__()". This method is deprecated. If no\n   "__delslice__()" is found, or for extended slicing of the form\n   "self[i:j:k]", a slice object is created, and passed to\n   "__delitem__()", instead of "__delslice__()" being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available.  For slice\noperations involving extended slice notation, or in absence of the\nslice methods, "__getitem__()", "__setitem__()" or "__delitem__()" is\ncalled with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n"__getitem__()", "__setitem__()" and "__delitem__()" support slice\nobjects as arguments):\n\n   class MyClass:\n       ...\n       def __getitem__(self, index):\n           ...\n       def __setitem__(self, index, value):\n           ...\n       def __delitem__(self, index):\n           ...\n\n       if sys.version_info < (2, 0):\n           # They won\'t be defined if version is at least 2.0 final\n\n           def __getslice__(self, i, j):\n               return self[max(0, i):max(0, j):]\n           def __setslice__(self, i, j, seq):\n               self[max(0, i):max(0, j):] = seq\n           def __delslice__(self, i, j):\n               del self[max(0, i):max(0, j):]\n       ...\n\nNote the calls to "max()"; these are necessary because of the handling\nof negative indices before the "__*slice__()" methods are called.\nWhen negative indexes are used, the "__*item__()" methods receive them\nas provided, but the "__*slice__()" methods get a "cooked" form of the\nindex values.  For each negative index value, the length of the\nsequence is added to the index before calling the method (which may\nstill result in a negative index); this is the customary handling of\nnegative indexes by the built-in sequence types, and the "__*item__()"\nmethods are expected to do this as well.  However, since they should\nalready be doing that, negative indexes cannot be passed in; they must\nbe constrained to the bounds of the sequence before being passed to\nthe "__*item__()" methods. Calling "max(0, i)" conveniently returns\nthe proper value.\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.__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 ("+", "-", "*", "//", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|").  For instance, to evaluate the\n   expression "x + y", where *x* is an instance of a class that has an\n   "__add__()" method, "x.__add__(y)" is called.  The "__divmod__()"\n   method should be the equivalent to using "__floordiv__()" and\n   "__mod__()"; it should not be related to "__truediv__()" (described\n   below).  Note that "__pow__()" should be defined to accept an\n   optional third argument if the ternary version of the built-in\n   "pow()" function 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.__div__(self, other)\nobject.__truediv__(self, other)\n\n   The division operator ("/") is implemented by these methods.  The\n   "__truediv__()" method is used when "__future__.division" is in\n   effect, otherwise "__div__()" is used.  If only one of these two\n   methods is defined, the object will not support division in the\n   alternate context; "TypeError" will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(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 ("+", "-", "*", "/", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|") with reflected (swapped) operands.\n   These functions are only called if the left operand does not\n   support the corresponding operation and the operands are of\n   different types. [2] For instance, to evaluate the expression "x -\n   y", where *y* is an instance of a class that has an "__rsub__()"\n   method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n   *NotImplemented*.\n\n   Note that ternary "pow()" will not try calling "__rpow__()" (the\n   coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left\n     operand\'s type and that subclass provides the reflected method\n     for the operation, this method will be called before the left\n     operand\'s non-reflected method.  This behavior allows subclasses\n     to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(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 should attempt to do the\n   operation in-place (modifying *self*) and return the result (which\n   could be, but does not have to be, *self*).  If a specific method\n   is not defined, the augmented assignment falls back to the normal\n   methods.  For instance, to execute the statement "x += y", where\n   *x* is an instance of a class that has an "__iadd__()" method,\n   "x.__iadd__(y)" is called.  If *x* is an instance of a class that\n   does not define a "__iadd__()" method, "x.__add__(y)" and\n   "y.__radd__(x)" are 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.__long__(self)\nobject.__float__(self)\n\n   Called to implement the built-in functions "complex()", "int()",\n   "long()", and "float()".  Should return a value of the appropriate\n   type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n   Called to implement the built-in functions "oct()" and "hex()".\n   Should return a string value.\n\nobject.__index__(self)\n\n   Called to implement "operator.index()".  Also called whenever\n   Python needs an integer object (such as in slicing).  Must return\n   an integer (int or long).\n\n   New in version 2.5.\n\nobject.__coerce__(self, other)\n\n   Called to implement "mixed-mode" numeric arithmetic.  Should either\n   return a 2-tuple containing *self* and *other* converted to a\n   common numeric type, or "None" if conversion is impossible.  When\n   the common type would be the type of "other", it is sufficient to\n   return "None", since the interpreter will also ask the other object\n   to attempt a coercion (but sometimes, if the implementation of the\n   other type cannot be changed, it is useful to do the conversion to\n   the other type here).  A return value of "NotImplemented" is\n   equivalent to returning "None".\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion.  As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable.  Instead, here are some informal\nguidelines regarding coercion.  In Python 3, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n  no coercion takes place and the string formatting operation is\n  invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n  mode operations on types that don\'t define coercion pass the\n  original arguments to the operation.\n\n* New-style classes (those derived from "object") never invoke the\n  "__coerce__()" method in response to a binary operator; the only\n  time "__coerce__()" is invoked is when the built-in function\n  "coerce()" is called.\n\n* For most intents and purposes, an operator that returns\n  "NotImplemented" is treated the same as one that is not implemented\n  at all.\n\n* Below, "__op__()" and "__rop__()" are used to signify the generic\n  method names corresponding to an operator; "__iop__()" is used for\n  the corresponding in-place operator.  For example, for the operator\n  \'"+"\', "__add__()" and "__radd__()" are used for the left and right\n  variant of the binary operator, and "__iadd__()" for the in-place\n  variant.\n\n* For objects *x* and *y*, first "x.__op__(y)" is tried.  If this is\n  not implemented or returns "NotImplemented", "y.__rop__(x)" is\n  tried.  If this is also not implemented or returns "NotImplemented",\n  a "TypeError" exception is raised.  But see the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n  of a built-in type or a new-style class, and the right operand is an\n  instance of a proper subclass of that type or class and overrides\n  the base\'s "__rop__()" method, the right operand\'s "__rop__()"\n  method is tried *before* the left operand\'s "__op__()" method.\n\n  This is done so that a subclass can completely override binary\n  operators. Otherwise, the left operand\'s "__op__()" method would\n  always accept the right operand: when an instance of a given class\n  is expected, an instance of a subclass of that class is always\n  acceptable.\n\n* When either operand type defines a coercion, this coercion is\n  called before that type\'s "__op__()" or "__rop__()" method is\n  called, but no sooner.  If the coercion returns an object of a\n  different type for the operand whose coercion is invoked, part of\n  the process is redone using the new object.\n\n* When an in-place operator (like \'"+="\') is used, if the left\n  operand implements "__iop__()", it is invoked without any coercion.\n  When the operation falls back to "__op__()" and/or "__rop__()", the\n  normal coercion rules apply.\n\n* In "x + y", if *x* is a sequence that implements sequence\n  concatenation, sequence concatenation is invoked.\n\n* In "x * y", if one operand is a sequence that implements sequence\n  repetition, and the other is an integer ("int" or "long"), sequence\n  repetition is invoked.\n\n* Rich comparisons (implemented by methods "__eq__()" and so on)\n  never use coercion.  Three-way comparison (implemented by\n  "__cmp__()") does use coercion under the same conditions as other\n  binary operations use it.\n\n* In the current implementation, the built-in numeric types "int",\n  "long", "float", and "complex" do not use coercion. All these types\n  implement a "__coerce__()" method, for use by the built-in\n  "coerce()" function.\n\n  Changed in version 2.7: The complex type no longer makes implicit\n  calls to the "__coerce__()" method for mixed-type binary arithmetic\n  operations.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section *The with\nstatement*), but can also be used by directly invoking their methods.\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: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nSpecial method lookup for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n"x.__getitem__(i)" or implicitly as in "x[i]".\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n   >>> class C:\n   ...     pass\n   ...\n   >>> c1 = C()\n   >>> c2 = C()\n   >>> c1.__len__ = lambda: 5\n   >>> c2.__len__ = lambda: 9\n   >>> len(c1)\n   5\n   >>> len(c2)\n   9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\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 by\nall objects, including type objects. If the implicit lookup of these\nmethods used the conventional lookup process, they would fail when\ninvoked 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):\n   ...     __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 provides\nsignificant scope for speed optimisations within the interpreter, at\nthe cost of some flexibility in the handling of special methods (the\nspecial method *must* be set on the class object itself in order to be\nconsistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type,\n    under certain controlled conditions. It generally isn\'t a good\n    idea though, since it can lead to some very strange behaviour if\n    it is 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 not\n    supported, which is why the reflected method is not called.\n',
- 'string-methods': u'\nString Methods\n**************\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.  Some of them are also available on\n"bytearray" objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the "%" operator described in the *String\nFormatting Operations* section. Also, see the "re" module for string\nfunctions based 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\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n   Decodes the string using the codec registered for *encoding*.\n   *encoding* defaults to the default string encoding.  *errors* may\n   be given to set a different error handling scheme.  The default is\n   "\'strict\'", meaning that encoding errors raise "UnicodeError".\n   Other possible values are "\'ignore\'", "\'replace\'" and any other\n   name registered via "codecs.register_error()", see section *Codec\n   Base Classes*.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for other error handling schemes\n   added.\n\n   Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string.  Default encoding is the\n   current default string encoding.  *errors* may be given to set a\n   different error handling scheme.  The default for *errors* is\n   "\'strict\'", meaning that encoding errors raise a "UnicodeError".\n   Other 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   New in version 2.0.\n\n   Changed in version 2.3: Support for "\'xmlcharrefreplace\'" and\n   "\'backslashreplace\'" and other error handling schemes added.\n\n   Changed in version 2.7: 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 suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\n   Changed in version 2.5: Accept tuples as *suffix*.\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.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\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\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\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\n   This method of string formatting is the new standard in Python 3,\n   and should be preferred to the "%" formatting described in *String\n   Formatting Operations* in new code.\n\n   New in version 2.6.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  The separator between elements is the\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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\n   New in version 2.5.\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* is\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\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\n   New in version 2.5.\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 splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\n   New in version 2.4.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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 or "-1", then there is\n   no limit 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* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   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   For example, "\' 1  2   3  \'.split()" returns "[\'1\', \'2\', \'3\']", and\n   "\'  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. This method uses the *universal newlines* approach to\n   splitting lines. Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   For example, "\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()" returns "[\'ab\n   c\', \'\', \'de fg\', \'kl\']", while the same call with\n   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']".\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\n   Changed in version 2.5: Accept tuples as *prefix*.\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 *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\n   Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n   Return a copy of the string where all characters occurring in the\n   optional argument *deletechars* are removed, and the remaining\n   characters have been mapped through the given translation table,\n   which must be a string of length 256.\n\n   You can use the "maketrans()" helper function in the "string"\n   module to create a translation table. For string objects, set the\n   *table* argument to "None" for translations that only delete\n   characters:\n\n   >>> \'read this short text\'.translate(None, \'aeiou\')\n   \'rd ths shrt txt\'\n\n   New in version 2.6: Support for a "None" *table* argument.\n\n   For Unicode objects, the "translate()" method does not accept the\n   optional *deletechars* argument.  Instead, it returns a copy of the\n   *s* where all characters have been mapped through the given\n   translation table which must be a mapping of Unicode ordinals to\n   Unicode ordinals, Unicode strings or "None". Unmapped characters\n   are left untouched. Characters mapped to "None" are deleted.  Note,\n   a more flexible approach is to create a custom character mapping\n   codec using the "codecs" module (see "encodings.cp1251" for an\n   example).\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   For 8-bit strings, this method is locale-dependent.\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 or equal to "len(s)".\n\n   New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n   Return "True" if there are only numeric characters in S, "False"\n   otherwise. Numeric characters include digit characters, and all\n   characters that have the Unicode numeric value property, e.g.\n   U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n   Return "True" if there are only decimal characters in S, "False"\n   otherwise. Decimal characters include digit characters, and all\n   characters that can be used to form decimal-radix numbers, e.g.\n   U+0660, ARABIC-INDIC DIGIT ZERO.\n',
- 'strings': u'\nString literals\n***************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"\n                    | "b" | "B" | "br" | "Br" | "bR" | "BR"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'"\n                  | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | escapeseq\n   longstringitem  ::= longstringchar | escapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   escapeseq       ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the "stringprefix" and the rest of\nthe string literal. The source character set is defined by the\nencoding declaration; it is ASCII if no encoding declaration is given\nin the source file; see section *Encoding declarations*.\n\nIn plain English: String literals can be enclosed in matching single\nquotes ("\'") or double quotes (""").  They can also be enclosed in\nmatching groups of three single or double quotes (these are generally\nreferred to as *triple-quoted strings*).  The backslash ("\\")\ncharacter is used to escape characters that otherwise have a special\nmeaning, such as newline, backslash itself, or the quote character.\nString literals may optionally be prefixed with a letter "\'r\'" or\n"\'R\'"; such strings are called *raw strings* and use different rules\nfor interpreting backslash escape sequences.  A prefix of "\'u\'" or\n"\'U\'" makes the string a Unicode string.  Unicode strings use the\nUnicode character set as defined by the Unicode Consortium and ISO\n10646.  Some additional escape sequences, described below, are\navailable in Unicode strings. A prefix of "\'b\'" or "\'B\'" is ignored in\nPython 2; it indicates that the literal should become a bytes literal\nin Python 3 (e.g. when code is automatically converted with 2to3).  A\n"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" prefix.\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"        | 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| "\\N{name}"        | Character named *name* in the     |         |\n|                   | Unicode database (Unicode only)   |         |\n+-------------------+-----------------------------------+---------+\n| "\\r"              | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\t"              | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\uxxxx"          | Character with 16-bit hex value   | (1)     |\n|                   | *xxxx* (Unicode only)             |         |\n+-------------------+-----------------------------------+---------+\n| "\\Uxxxxxxxx"      | Character with 32-bit hex value   | (2)     |\n|                   | *xxxxxxxx* (Unicode only)         |         |\n+-------------------+-----------------------------------+---------+\n| "\\v"              | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| "\\ooo"            | Character with octal value *ooo*  | (3,5)   |\n+-------------------+-----------------------------------+---------+\n| "\\xhh"            | Character with hex value *hh*     | (4,5)   |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. Individual code units which form parts of a surrogate pair can\n   be encoded using this escape sequence.\n\n2. 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).\n\n3. As in Standard C, up to three octal digits are accepted.\n\n4. Unlike in Standard C, exactly two hex digits are required.\n\n5. In a string literal, hexadecimal and octal escapes denote the\n   byte with the given value; it is not necessary that the byte\n   encodes a character in the source character set. In a Unicode\n   literal, these escapes denote a Unicode character with the given\n   value.\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 marked as "(Unicode only)"\nin the table above fall into the category of unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an "\'r\'" or "\'R\'" prefix is present, a character following a\nbackslash is included in the string without change, and *all\nbackslashes are left in the string*.  For example, the string literal\n"r"\\n"" consists of two characters: a backslash and a lowercase "\'n\'".\nString quotes can be escaped with a backslash, but the backslash\nremains in the string; for example, "r"\\""" is a valid string literal\nconsisting of two characters: a backslash and a double quote; "r"\\""\nis not a valid string literal (even a raw string cannot end in an odd\nnumber of backslashes).  Specifically, *a raw string cannot end in a\nsingle backslash* (since the backslash would escape the following\nquote character).  Note also that a single backslash followed by a\nnewline is interpreted as those two characters as part of the string,\n*not* as a line continuation.\n\nWhen an "\'r\'" or "\'R\'" prefix is used in conjunction with a "\'u\'" or\n"\'U\'" prefix, then the "\\uXXXX" and "\\UXXXXXXXX" escape sequences are\nprocessed while  *all other backslashes are left in the string*. For\nexample, the string literal "ur"\\u0062\\n"" consists of three Unicode\ncharacters: \'LATIN SMALL LETTER B\', \'REVERSE SOLIDUS\', and \'LATIN\nSMALL LETTER N\'. Backslashes can be escaped with a preceding\nbackslash; however, both remain in the string.  As a result, "\\uXXXX"\nescape sequences are only recognized when there are an odd number of\nbackslashes.\n',
+ 'slicings': u'\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 slicing:\n\n   slicing          ::= simple_slicing | extended_slicing\n   simple_slicing   ::= primary "[" short_slice "]"\n   extended_slicing ::= primary "[" slice_list "]"\n   slice_list       ::= slice_item ("," slice_item)* [","]\n   slice_item       ::= expression | proper_slice | ellipsis\n   proper_slice     ::= short_slice | long_slice\n   short_slice      ::= [lower_bound] ":" [upper_bound]\n   long_slice       ::= short_slice ":" [stride]\n   lower_bound      ::= expression\n   upper_bound      ::= expression\n   stride           ::= expression\n   ellipsis         ::= "..."\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 nor ellipses).  Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\n\nThe semantics for a simple slicing are as follows.  The primary must\nevaluate to a sequence object.  The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n"sys.maxint", respectively.  If either bound is negative, the\nsequence\'s length is added to it.  The slicing now selects all items\nwith index *k* such that "i <= k < j" where *i* and *j* are the\nspecified lower and upper bounds.  This may be an empty sequence.  It\nis not an error if *i* or *j* lie outside the range of valid indexes\n(such items don\'t exist so they aren\'t selected).\n\nThe semantics for an extended slicing are as follows.  The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed 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 an ellipsis slice\nitem is the built-in "Ellipsis" object.  The conversion of a proper\nslice is a slice object (see section The standard type hierarchy)\nwhose "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': u'\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\nobject.__methods__\n\n   Deprecated since version 2.2: Use the built-in function "dir()" to\n   get a list of an object\'s attributes. This attribute is no longer\n   available.\n\nobject.__members__\n\n   Deprecated since version 2.2: Use the built-in function "dir()" to\n   get a list of an object\'s attributes. This attribute is no longer\n   available.\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\n    in 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] Cased characters are those with general category property\n    being one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase),\n    or "Lt" (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a\n    singleton tuple whose only element is the tuple to be formatted.\n\n[6] The advantage of leaving the newline on is that returning an\n    empty string is then an unambiguous EOF indication.  It is also\n    possible (in cases where it might matter, for example, if you want\n    to make an exact copy of a file while scanning its lines) to tell\n    whether the last line of a file ended in a newline or not (yes\n    this happens!).\n',
+ 'specialnames': u'\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 class,\nthen "x[i]" is roughly equivalent to "x.__getitem__(i)" for old-style\nclasses and "type(x).__getitem__(x, i)" for new-style classes.  Except\nwhere mentioned, attempts to execute an operation raise an exception\nwhen no appropriate method is defined (typically "AttributeError" or\n"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 an\n   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 after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  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, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customise\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "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, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__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 is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_traceback" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     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.exc_traceback" or "sys.last_traceback".  Circular references\n     which are garbage are detected when the option cycle detector is\n     enabled (it\'s on by default), but can only be cleaned up if there\n     are no Python-level "__del__()" methods involved. Refer to the\n     documentation 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\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python 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\n   See also the "-R" command-line option.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function and by string conversions\n   (reverse quotes) to compute the "official" string representation of\n   an object.  If at all possible, this should look like a valid\n   Python expression that could be used to recreate an object with the\n   same value (given an appropriate environment).  If this is not\n   possible, a string of the form "<...some useful description...>"\n   should be returned.  The return value must be a string object. If a\n   class defines "__repr__()" but not "__str__()", then "__repr__()"\n   is also used when an "informal" string representation of instances\n   of that class is 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   statement to compute the "informal" string representation of an\n   object.  This differs from "__repr__()" in that it does not have to\n   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.__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   New in version 2.1.\n\n   These are the so-called "rich comparison" methods, and are called\n   for comparison operators in preference to "__cmp__()" below. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" and "x<>y" call "x.__ne__(y)",\n   "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result 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 the\n   paragraph on "__hash__()" for some important notes on creating\n   *hashable* objects which support custom comparison operations and\n   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 other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own 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.__cmp__(self, other)\n\n   Called by comparison operations if rich comparison (see above) is\n   not defined.  Should return a negative integer if "self < other",\n   zero if "self == other", a positive integer if "self > other".  If\n   no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n   class instances are compared by object identity ("address").  See\n   also the description of "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys. (Note: the\n   restriction that exceptions are not propagated by "__cmp__()" has\n   been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n   Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   If a class does not define a "__cmp__()" or "__eq__()" method it\n   should not define a "__hash__()" operation either; if it defines\n   "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n   not be usable in hashed collections.  If a class defines mutable\n   objects and implements a "__cmp__()" or "__eq__()" method, it\n   should not implement "__hash__()", since hashable collection\n   implementations require that a object\'s hash value is immutable (if\n   the object\'s hash value changes, it will be in the wrong hash\n   bucket).\n\n   User-defined classes have "__cmp__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns a result derived from\n   "id(x)".\n\n   Classes which inherit a "__hash__()" method from a parent class but\n   change the meaning of "__cmp__()" or "__eq__()" such that the hash\n   value returned is no longer appropriate (e.g. by switching to a\n   value-based concept of equality instead of the default identity\n   based equality) can explicitly flag themselves as being unhashable\n   by setting "__hash__ = None" in the class definition. Doing so\n   means that not only will instances of the class raise an\n   appropriate "TypeError" when a program attempts to retrieve their\n   hash value, but they will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)"\n   (unlike classes which define their own "__hash__()" to explicitly\n   raise "TypeError").\n\n   Changed in version 2.5: "__hash__()" may now also return a long\n   integer object; the 32-bit integer is then derived from the hash of\n   that object.\n\n   Changed in version 2.6: "__hash__" may now be set to "None" to\n   explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True", or their integer\n   equivalents "0" or "1".  When this method is not defined,\n   "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero. If a class defines\n   neither "__len__()" nor "__nonzero__()", all its instances are\n   considered true.\n\nobject.__unicode__(self)\n\n   Called to implement "unicode()" built-in; should return a Unicode\n   object. When this method is not defined, string conversion is\n   attempted, and the result of string conversion is converted to\n   Unicode using the system default encoding.\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") for\nclass 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. This\n   method should return the (computed) attribute value or raise an\n   "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 for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   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 in new-style classes.\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 not simply execute "self.name = value" --- this would cause\n   a recursive call to itself.  Instead, it should insert the value in\n   the dictionary of instance attributes, e.g., "self.__dict__[name] =\n   value".  For new-style classes, rather than accessing the instance\n   dictionary, it should call the base class method with the same\n   name, for example, "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\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See Special method lookup for new-style\n     classes.\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 an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  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 "AttributeError"\n   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, it\nis 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.  Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe 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 a new-style object instance, "a.x" is transformed\n   into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a new-style class, "A.x" is transformed into the\n   call: "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 "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\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__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented 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 both old and new-style classes have a\ndictionary for attribute storage.  This wastes space for objects\nhaving very few instance variables.  The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition.  The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable.  Space is saved because *__dict__* is\nnot created for each instance.\n\n__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   new-style class, *__slots__* reserves space for the declared\n   variables and prevents the automatic creation of *__dict__* and\n   *__weakref__* for each instance.\n\n   New in version 2.2.\n\nNotes on using *__slots__*\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  Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n  *__slots__* declaration would not enable the assignment of new\n  attributes not specifically listed in the sequence of instance\n  variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n  Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n  *__slots__* declaration would not enable support for weak\n  references.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (Implementing Descriptors) for each variable name.  As a\n  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\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This 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 "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may 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  Changed in version 2.6: Previously, *__class__* assignment raised an\n  error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style 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 *__metaclass__* is defined then\nthe callable assigned to it will be called instead of "type()". 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\n  the 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\n__metaclass__\n\n   This variable can be any callable accepting arguments for "name",\n   "bases", and "dict".  Upon class creation, the callable is used\n   instead of the built-in "type()".\n\n   New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If "dict[\'__metaclass__\']" exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used (this looks for a *__class__* attribute first and if not found,\n  uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n  used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n  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\n\nCustomizing instance and subclass checks\n========================================\n\nNew in version 2.6.\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 in\norder 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: **PEP 3119** - Introducing Abstract Base Classes\n\n     Includes the specification for customizing "isinstance()" and\n     "issubclass()" behavior through "__instancecheck__()" and\n     "__subclasscheck__()", with motivation for this functionality in\n     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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects.  The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects.  Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__coerce__()" or other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values.  It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n   doesn\'t define a "__nonzero__()" method and whose "__len__()"\n   method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" 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.__missing__(self, key)\n\n   Called by "dict"."__getitem__()" to implement "self[key]" for dict\n   subclasses when key is not in the dictionary.\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__()" 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 "iterkeys()".\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 "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\n   New in version 2.6.\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 test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see this section in the\n   language reference.\n\n\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects.  Immutable sequences methods should at most only\ndefine "__getslice__()"; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n   Deprecated since version 2.0: Support slice objects as parameters\n   to the "__getitem__()" method. (However, built-in types in CPython\n   currently still implement "__getslice__()".  Therefore, you have to\n   override it in derived classes when implementing slicing.)\n\n   Called to implement evaluation of "self[i:j]". The returned object\n   should be of the same type as *self*.  Note that missing *i* or *j*\n   in the slice expression are replaced by zero or "sys.maxsize",\n   respectively.  If negative indexes are used in the slice, the\n   length of the sequence is added to that index. If the instance does\n   not implement the "__len__()" method, an "AttributeError" is\n   raised. No guarantee is made that indexes adjusted this way are not\n   still negative.  Indexes which are greater than the length of the\n   sequence are not modified. If no "__getslice__()" is found, a slice\n   object is created instead, and passed to "__getitem__()" instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n   Called to implement assignment to "self[i:j]". Same notes for *i*\n   and *j* as for "__getslice__()".\n\n   This method is deprecated. If no "__setslice__()" is found, or for\n   extended slicing of the form "self[i:j:k]", a slice object is\n   created, and passed to "__setitem__()", instead of "__setslice__()"\n   being called.\n\nobject.__delslice__(self, i, j)\n\n   Called to implement deletion of "self[i:j]". Same notes for *i* and\n   *j* as for "__getslice__()". This method is deprecated. If no\n   "__delslice__()" is found, or for extended slicing of the form\n   "self[i:j:k]", a slice object is created, and passed to\n   "__delitem__()", instead of "__delslice__()" being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available.  For slice\noperations involving extended slice notation, or in absence of the\nslice methods, "__getitem__()", "__setitem__()" or "__delitem__()" is\ncalled with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n"__getitem__()", "__setitem__()" and "__delitem__()" support slice\nobjects as arguments):\n\n   class MyClass:\n       ...\n       def __getitem__(self, index):\n           ...\n       def __setitem__(self, index, value):\n           ...\n       def __delitem__(self, index):\n           ...\n\n       if sys.version_info < (2, 0):\n           # They won\'t be defined if version is at least 2.0 final\n\n           def __getslice__(self, i, j):\n               return self[max(0, i):max(0, j):]\n           def __setslice__(self, i, j, seq):\n               self[max(0, i):max(0, j):] = seq\n           def __delslice__(self, i, j):\n               del self[max(0, i):max(0, j):]\n       ...\n\nNote the calls to "max()"; these are necessary because of the handling\nof negative indices before the "__*slice__()" methods are called.\nWhen negative indexes are used, the "__*item__()" methods receive them\nas provided, but the "__*slice__()" methods get a "cooked" form of the\nindex values.  For each negative index value, the length of the\nsequence is added to the index before calling the method (which may\nstill result in a negative index); this is the customary handling of\nnegative indexes by the built-in sequence types, and the "__*item__()"\nmethods are expected to do this as well.  However, since they should\nalready be doing that, negative indexes cannot be passed in; they must\nbe constrained to the bounds of the sequence before being passed to\nthe "__*item__()" methods. Calling "max(0, i)" conveniently returns\nthe proper value.\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.__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 ("+", "-", "*", "//", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|").  For instance, to evaluate the\n   expression "x + y", where *x* is an instance of a class that has an\n   "__add__()" method, "x.__add__(y)" is called.  The "__divmod__()"\n   method should be the equivalent to using "__floordiv__()" and\n   "__mod__()"; it should not be related to "__truediv__()" (described\n   below).  Note that "__pow__()" should be defined to accept an\n   optional third argument if the ternary version of the built-in\n   "pow()" function 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.__div__(self, other)\nobject.__truediv__(self, other)\n\n   The division operator ("/") is implemented by these methods.  The\n   "__truediv__()" method is used when "__future__.division" is in\n   effect, otherwise "__div__()" is used.  If only one of these two\n   methods is defined, the object will not support division in the\n   alternate context; "TypeError" will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(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 ("+", "-", "*", "/", "%", "divmod()", "pow()", "**",\n   "<<", ">>", "&", "^", "|") with reflected (swapped) operands.\n   These functions are only called if the left operand does not\n   support the corresponding operation and the operands are of\n   different types. [2] For instance, to evaluate the expression "x -\n   y", where *y* is an instance of a class that has an "__rsub__()"\n   method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n   *NotImplemented*.\n\n   Note that ternary "pow()" will not try calling "__rpow__()" (the\n   coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left\n     operand\'s type and that subclass provides the reflected method\n     for the operation, this method will be called before the left\n     operand\'s non-reflected method.  This behavior allows subclasses\n     to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(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 should attempt to do the\n   operation in-place (modifying *self*) and return the result (which\n   could be, but does not have to be, *self*).  If a specific method\n   is not defined, the augmented assignment falls back to the normal\n   methods.  For instance, to execute the statement "x += y", where\n   *x* is an instance of a class that has an "__iadd__()" method,\n   "x.__iadd__(y)" is called.  If *x* is an instance of a class that\n   does not define a "__iadd__()" method, "x.__add__(y)" and\n   "y.__radd__(x)" are 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.__long__(self)\nobject.__float__(self)\n\n   Called to implement the built-in functions "complex()", "int()",\n   "long()", and "float()".  Should return a value of the appropriate\n   type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n   Called to implement the built-in functions "oct()" and "hex()".\n   Should return a string value.\n\nobject.__index__(self)\n\n   Called to implement "operator.index()".  Also called whenever\n   Python needs an integer object (such as in slicing).  Must return\n   an integer (int or long).\n\n   New in version 2.5.\n\nobject.__coerce__(self, other)\n\n   Called to implement "mixed-mode" numeric arithmetic.  Should either\n   return a 2-tuple containing *self* and *other* converted to a\n   common numeric type, or "None" if conversion is impossible.  When\n   the common type would be the type of "other", it is sufficient to\n   return "None", since the interpreter will also ask the other object\n   to attempt a coercion (but sometimes, if the implementation of the\n   other type cannot be changed, it is useful to do the conversion to\n   the other type here).  A return value of "NotImplemented" is\n   equivalent to returning "None".\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion.  As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable.  Instead, here are some informal\nguidelines regarding coercion.  In Python 3, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n  no coercion takes place and the string formatting operation is\n  invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n  mode operations on types that don\'t define coercion pass the\n  original arguments to the operation.\n\n* New-style classes (those derived from "object") never invoke the\n  "__coerce__()" method in response to a binary operator; the only\n  time "__coerce__()" is invoked is when the built-in function\n  "coerce()" is called.\n\n* For most intents and purposes, an operator that returns\n  "NotImplemented" is treated the same as one that is not implemented\n  at all.\n\n* Below, "__op__()" and "__rop__()" are used to signify the generic\n  method names corresponding to an operator; "__iop__()" is used for\n  the corresponding in-place operator.  For example, for the operator\n  \'"+"\', "__add__()" and "__radd__()" are used for the left and right\n  variant of the binary operator, and "__iadd__()" for the in-place\n  variant.\n\n* For objects *x* and *y*, first "x.__op__(y)" is tried.  If this is\n  not implemented or returns "NotImplemented", "y.__rop__(x)" is\n  tried.  If this is also not implemented or returns "NotImplemented",\n  a "TypeError" exception is raised.  But see the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n  of a built-in type or a new-style class, and the right operand is an\n  instance of a proper subclass of that type or class and overrides\n  the base\'s "__rop__()" method, the right operand\'s "__rop__()"\n  method is tried *before* the left operand\'s "__op__()" method.\n\n  This is done so that a subclass can completely override binary\n  operators. Otherwise, the left operand\'s "__op__()" method would\n  always accept the right operand: when an instance of a given class\n  is expected, an instance of a subclass of that class is always\n  acceptable.\n\n* When either operand type defines a coercion, this coercion is\n  called before that type\'s "__op__()" or "__rop__()" method is\n  called, but no sooner.  If the coercion returns an object of a\n  different type for the operand whose coercion is invoked, part of\n  the process is redone using the new object.\n\n* When an in-place operator (like \'"+="\') is used, if the left\n  operand implements "__iop__()", it is invoked without any coercion.\n  When the operation falls back to "__op__()" and/or "__rop__()", the\n  normal coercion rules apply.\n\n* In "x + y", if *x* is a sequence that implements sequence\n  concatenation, sequence concatenation is invoked.\n\n* In "x * y", if one operand is a sequence that implements sequence\n  repetition, and the other is an integer ("int" or "long"), sequence\n  repetition is invoked.\n\n* Rich comparisons (implemented by methods "__eq__()" and so on)\n  never use coercion.  Three-way comparison (implemented by\n  "__cmp__()") does use coercion under the same conditions as other\n  binary operations use it.\n\n* In the current implementation, the built-in numeric types "int",\n  "long", "float", and "complex" do not use coercion. All these types\n  implement a "__coerce__()" method, for use by the built-in\n  "coerce()" function.\n\n  Changed in version 2.7: The complex type no longer makes implicit\n  calls to the "__coerce__()" method for mixed-type binary arithmetic\n  operations.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section The with\nstatement), but can also be used by directly invoking their methods.\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: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nSpecial method lookup for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n"x.__getitem__(i)" or implicitly as in "x[i]".\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n   >>> class C:\n   ...     pass\n   ...\n   >>> c1 = C()\n   >>> c2 = C()\n   >>> c1.__len__ = lambda: 5\n   >>> c2.__len__ = lambda: 9\n   >>> len(c1)\n   5\n   >>> len(c2)\n   9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\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 by\nall objects, including type objects. If the implicit lookup of these\nmethods used the conventional lookup process, they would fail when\ninvoked 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):\n   ...     __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 provides\nsignificant scope for speed optimisations within the interpreter, at\nthe cost of some flexibility in the handling of special methods (the\nspecial method *must* be set on the class object itself in order to be\nconsistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type,\n    under certain controlled conditions. It generally isn\'t a good\n    idea though, since it can lead to some very strange behaviour if\n    it is 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 not\n    supported, which is why the reflected method is not called.\n',
+ 'string-methods': u'\nString Methods\n**************\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.  Some of them are also available on\n"bytearray" objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange section. To output formatted strings use\ntemplate strings or the "%" operator described in the String\nFormatting Operations section. Also, see the "re" module for string\nfunctions based 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\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n   Decodes the string using the codec registered for *encoding*.\n   *encoding* defaults to the default string encoding.  *errors* may\n   be given to set a different error handling scheme.  The default is\n   "\'strict\'", meaning that encoding errors raise "UnicodeError".\n   Other possible values are "\'ignore\'", "\'replace\'" and any other\n   name registered via "codecs.register_error()", see section Codec\n   Base Classes.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for other error handling schemes\n   added.\n\n   Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string.  Default encoding is the\n   current default string encoding.  *errors* may be given to set a\n   different error handling scheme.  The default for *errors* is\n   "\'strict\'", meaning that encoding errors raise a "UnicodeError".\n   Other 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   New in version 2.0.\n\n   Changed in version 2.3: Support for "\'xmlcharrefreplace\'" and\n   "\'backslashreplace\'" and other error handling schemes added.\n\n   Changed in version 2.7: 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 suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\n   Changed in version 2.5: Accept tuples as *suffix*.\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.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\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\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\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\n   This method of string formatting is the new standard in Python 3,\n   and should be preferred to the "%" formatting described in String\n   Formatting Operations in new code.\n\n   New in version 2.6.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  The separator between elements is the\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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\n   New in version 2.5.\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* is\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\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\n   New in version 2.5.\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 splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\n   New in version 2.4.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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 or "-1", then there is\n   no limit 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* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   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   For example, "\' 1  2   3  \'.split()" returns "[\'1\', \'2\', \'3\']", and\n   "\'  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. This method uses the *universal newlines* approach to\n   splitting lines. Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   For example, "\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()" returns "[\'ab\n   c\', \'\', \'de fg\', \'kl\']", while the same call with\n   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']".\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\n   Changed in version 2.5: Accept tuples as *prefix*.\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 *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\n   Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n   Return a copy of the string where all characters occurring in the\n   optional argument *deletechars* are removed, and the remaining\n   characters have been mapped through the given translation table,\n   which must be a string of length 256.\n\n   You can use the "maketrans()" helper function in the "string"\n   module to create a translation table. For string objects, set the\n   *table* argument to "None" for translations that only delete\n   characters:\n\n   >>> \'read this short text\'.translate(None, \'aeiou\')\n   \'rd ths shrt txt\'\n\n   New in version 2.6: Support for a "None" *table* argument.\n\n   For Unicode objects, the "translate()" method does not accept the\n   optional *deletechars* argument.  Instead, it returns a copy of the\n   *s* where all characters have been mapped through the given\n   translation table which must be a mapping of Unicode ordinals to\n   Unicode ordinals, Unicode strings or "None". Unmapped characters\n   are left untouched. Characters mapped to "None" are deleted.  Note,\n   a more flexible approach is to create a custom character mapping\n   codec using the "codecs" module (see "encodings.cp1251" for an\n   example).\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   For 8-bit strings, this method is locale-dependent.\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 or equal to "len(s)".\n\n   New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n   Return "True" if there are only numeric characters in S, "False"\n   otherwise. Numeric characters include digit characters, and all\n   characters that have the Unicode numeric value property, e.g.\n   U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n   Return "True" if there are only decimal characters in S, "False"\n   otherwise. Decimal characters include digit characters, and all\n   characters that can be used to form decimal-radix numbers, e.g.\n   U+0660, ARABIC-INDIC DIGIT ZERO.\n',
+ 'strings': u'\nString literals\n***************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"\n                    | "b" | "B" | "br" | "Br" | "bR" | "BR"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'"\n                  | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | escapeseq\n   longstringitem  ::= longstringchar | escapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   escapeseq       ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the "stringprefix" and the rest of\nthe string literal. The source character set is defined by the\nencoding declaration; it is ASCII if no encoding declaration is given\nin the source file; see section Encoding declarations.\n\nIn plain English: String literals can be enclosed in matching single\nquotes ("\'") or double quotes (""").  They can also be enclosed in\nmatching groups of three single or double quotes (these are generally\nreferred to as *triple-quoted strings*).  The backslash ("\\")\ncharacter is used to escape characters that otherwise have a special\nmeaning, such as newline, backslash itself, or the quote character.\nString literals may optionally be prefixed with a letter "\'r\'" or\n"\'R\'"; such strings are called *raw strings* and use different rules\nfor interpreting backslash escape sequences.  A prefix of "\'u\'" or\n"\'U\'" makes the string a Unicode string.  Unicode strings use the\nUnicode character set as defined by the Unicode Consortium and ISO\n10646.  Some additional escape sequences, described below, are\navailable in Unicode strings. A prefix of "\'b\'" or "\'B\'" is ignored in\nPython 2; it indicates that the literal should become a bytes literal\nin Python 3 (e.g. when code is automatically converted with 2to3).  A\n"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" prefix.\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"        | 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| "\\N{name}"        | Character named *name* in the     |         |\n|                   | Unicode database (Unicode only)   |         |\n+-------------------+-----------------------------------+---------+\n| "\\r"              | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\t"              | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\uxxxx"          | Character with 16-bit hex value   | (1)     |\n|                   | *xxxx* (Unicode only)             |         |\n+-------------------+-----------------------------------+---------+\n| "\\Uxxxxxxxx"      | Character with 32-bit hex value   | (2)     |\n|                   | *xxxxxxxx* (Unicode only)         |         |\n+-------------------+-----------------------------------+---------+\n| "\\v"              | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| "\\ooo"            | Character with octal value *ooo*  | (3,5)   |\n+-------------------+-----------------------------------+---------+\n| "\\xhh"            | Character with hex value *hh*     | (4,5)   |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. Individual code units which form parts of a surrogate pair can\n   be encoded using this escape sequence.\n\n2. 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).\n\n3. As in Standard C, up to three octal digits are accepted.\n\n4. Unlike in Standard C, exactly two hex digits are required.\n\n5. In a string literal, hexadecimal and octal escapes denote the\n   byte with the given value; it is not necessary that the byte\n   encodes a character in the source character set. In a Unicode\n   literal, these escapes denote a Unicode character with the given\n   value.\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 marked as "(Unicode only)"\nin the table above fall into the category of unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an "\'r\'" or "\'R\'" prefix is present, a character following a\nbackslash is included in the string without change, and *all\nbackslashes are left in the string*.  For example, the string literal\n"r"\\n"" consists of two characters: a backslash and a lowercase "\'n\'".\nString quotes can be escaped with a backslash, but the backslash\nremains in the string; for example, "r"\\""" is a valid string literal\nconsisting of two characters: a backslash and a double quote; "r"\\""\nis not a valid string literal (even a raw string cannot end in an odd\nnumber of backslashes).  Specifically, *a raw string cannot end in a\nsingle backslash* (since the backslash would escape the following\nquote character).  Note also that a single backslash followed by a\nnewline is interpreted as those two characters as part of the string,\n*not* as a line continuation.\n\nWhen an "\'r\'" or "\'R\'" prefix is used in conjunction with a "\'u\'" or\n"\'U\'" prefix, then the "\\uXXXX" and "\\UXXXXXXXX" escape sequences are\nprocessed while  *all other backslashes are left in the string*. For\nexample, the string literal "ur"\\u0062\\n"" consists of three Unicode\ncharacters: \'LATIN SMALL LETTER B\', \'REVERSE SOLIDUS\', and \'LATIN\nSMALL LETTER N\'. Backslashes can be escaped with a preceding\nbackslash; however, both remain in the string.  As a result, "\\uXXXX"\nescape sequences are only recognized when there are an odd number of\nbackslashes.\n',
  'subscriptions': u'\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 of a sequence or mapping type.\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 a\nplain integer.  If this value is negative, the length of the sequence\nis added to it (so that, e.g., "x[-1]" selects the last item of "x".)\nThe resulting value must be a nonnegative integer less than the number\nof items in the sequence, and the subscription selects the item whose\nindex is that value (counting from zero).\n\nA string\'s items are characters.  A character is not a separate data\ntype but a string of exactly one character.\n',
  'truth': u'\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", "0L", "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  "__nonzero__()" 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, unless\notherwise stated. (Important exception: the Boolean operations "or"\nand "and" always return one of their operands.)\n',
- 'try': u'\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" | ",") identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n"try"..."except"..."finally" did not work. "try"..."except" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified in that except clause, if present, and the except\nclause\'s suite is executed.  All except clauses must have an\nexecutable block.  When the end of this block is reached, execution\ncontinues normally after the entire try statement.  (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the "sys" module:\n"sys.exc_type" receives the object identifying the exception;\n"sys.exc_value" receives the exception\'s parameter;\n"sys.exc_traceback" receives a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. These details are also available through the\n"sys.exc_info()" function, which returns a tuple "(exc_type,\nexc_value, exc_traceback)".  Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program.  As of Python 1.5, the variables 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\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': u'\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.).\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". It\n   is used to signify the absence of a value in many situations, e.g.,\n   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 built-in name\n   "Ellipsis". It is used to indicate the presence of the "..." syntax\n   in a slice.  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 three types of integers:\n\n      Plain integers\n         These represent numbers in the range -2147483648 through\n         2147483647. (The range may be larger on machines with a\n         larger natural word size, but not smaller.)  When the result\n         of an operation would fall outside this range, the result is\n         normally returned as a long integer (in some cases, the\n         exception "OverflowError" is raised instead).  For the\n         purpose of shift and mask operations, integers are assumed to\n         have a binary, 2\'s complement notation using 32 or more bits,\n         and hiding no bits from the user (i.e., all 4294967296\n         different bit patterns correspond to different values).\n\n      Long integers\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\n         These represent the truth values False and True.  The two\n         objects representing the values "False" and "True" are the\n         only Boolean objects. The Boolean type is a subtype of plain\n         integers, 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 and the least surprises when\n      switching between the plain and long integer domains.  Any\n      operation, if it yields a result in the plain integer domain,\n      will yield the same result in the long integer domain or when\n      using mixed operands.  The switch between domains is transparent\n      to the programmer.\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 are\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"\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 items\n   of a sequence. When the length of a sequence is *n*, the index set\n   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is\n   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* where\n   "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *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 are characters.  There is no separate\n         character type; a character is represented by a string of one\n         item. Characters represent (at least) 8-bit bytes.  The\n         built-in functions "chr()" and "ord()" convert between\n         characters and nonnegative integers representing the byte\n         values.  Bytes with the values 0-127 usually represent the\n         corresponding ASCII values, but the interpretation of values\n         is up to the program.  The string data type is also used to\n         represent arrays of bytes, e.g., to hold data read from a\n         file.\n\n         (On systems whose native character set is not ASCII, strings\n         may use EBCDIC in their internal representation, provided the\n         functions "chr()" and "ord()" implement a mapping between\n         ASCII and EBCDIC, and string comparison preserves the ASCII\n         order. Or perhaps someone can propose a better rule?)\n\n      Unicode\n         The items of a Unicode object are Unicode code units.  A\n         Unicode code unit is represented by a Unicode 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 "unichr()" 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 Unicode method "encode()" and the built-\n         in function "unicode()".\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   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 a\n      mutable sequence type.\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 immutable\n      and *hashable*, it can be used again as an element of another\n      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 "k"\n   from the mapping "a"; this can be used in expressions and as the\n   target of assignments or "del" statements. The built-in function\n   "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 "1.0")\n      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", "gdbm", and "bsddb" provide\n      additional examples of mapping types.\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__" "func_doc"    | The function\'s documentation    | Writable    |\n      |                         | string, or "None" if            |             |\n      |                         | unavailable.                    |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__name__" "func_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      | "func_defaults"         | argument values for those       |             |\n      |                         | arguments that have defaults,   |             |\n      |                         | or "None" if no arguments have  |             |\n      |                         | a default value.                |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__code__" "func_code"  | The code object representing    | Writable    |\n      |                         | the compiled function body.     |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__globals__"           | A reference to the dictionary   | Read-only   |\n      | "func_globals"          | 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__" "func_dict"  | The namespace supporting        | Writable    |\n      |                         | arbitrary function attributes.  |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__closure__"           | "None" or a tuple of cells that | Read-only   |\n      | "func_closure"          | contain bindings for the        |             |\n      |                         | function\'s free variables.      |             |\n      +-------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Changed in version 2.4: "func_name" is now writable.\n\n      Changed in version 2.6: The double-underscore attributes\n      "__closure__", "__code__", "__defaults__", and "__globals__"\n      were introduced as aliases for the corresponding "func_*"\n      attributes for forwards compatibility with Python 3.\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   User-defined methods\n      A user-defined method object combines a class, a class instance\n      (or "None") and any callable object (normally a user-defined\n      function).\n\n      Special read-only attributes: "im_self" is the class instance\n      object, "im_func" is the function object; "im_class" is the\n      class of "im_self" for bound methods or the class that asked for\n      the method for unbound methods; "__doc__" is the method\'s\n      documentation (same as "im_func.__doc__"); "__name__" is the\n      method name (same as "im_func.__name__"); "__module__" is the\n      name of the module the method was defined in, or "None" if\n      unavailable.\n\n      Changed in version 2.2: "im_self" used to refer to the class\n      that defined the method.\n\n      Changed in version 2.6: For Python 3 forward-compatibility,\n      "im_func" is also available as "__func__", and "im_self" as\n      "__self__".\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, an unbound\n      user-defined method object, or a class method object. When the\n      attribute is a user-defined method object, a new method object\n      is only created if the class from which it is being retrieved is\n      the same as, or a derived class of, the class stored in the\n      original method object; otherwise, the original method object is\n      used as it is.\n\n      When a user-defined method object is created by retrieving a\n      user-defined function object from a class, its "im_self"\n      attribute is "None" and the method object is said to be unbound.\n      When one is created by retrieving a user-defined function object\n      from a class via one of its instances, its "im_self" attribute\n      is the instance, and the method object is said to be bound. In\n      either case, the new method\'s "im_class" attribute is the class\n      from which the retrieval takes place, and its "im_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 "im_func"\n      attribute of the new instance is not the original method object\n      but its "im_func" attribute.\n\n      When a user-defined method object is created by retrieving a\n      class method object from a class or instance, its "im_self"\n      attribute is the class itself, and its "im_func" attribute is\n      the function object underlying the class method.\n\n      When an unbound user-defined method object is called, the\n      underlying function ("im_func") is called, with the restriction\n      that the first argument must be an instance of the proper class\n      ("im_class") or of a derived class thereof.\n\n      When a bound user-defined method object is called, the\n      underlying function ("im_func") is called, inserting the class\n      instance ("im_self") in front of the argument list.  For\n      instance, when "C" is a class which contains a definition for a\n      function "f()", and "x" is an instance of "C", calling "x.f(1)"\n      is equivalent to calling "C.f(x, 1)".\n\n      When a user-defined method object is derived from a class method\n      object, the "class instance" stored in "im_self" will actually\n      be the class itself, so that calling either "x.f(1)" or "C.f(1)"\n      is equivalent to calling "f(C,1)" where "f" is the underlying\n      function.\n\n      Note that the transformation from function object to (unbound or\n      bound) method object happens each time the attribute is\n      retrieved from the class or instance. In some cases, a fruitful\n      optimization is to assign the attribute to a local variable and\n      call that local variable. Also notice that this transformation\n      only happens for user-defined functions; other callable objects\n      (and all non-callable objects) are retrieved without\n      transformation.  It is also important to note that user-defined\n      functions which are attributes of a class instance are not\n      converted to bound methods; this *only* happens when the\n      function is an attribute 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 the\n      end, a "StopIteration" exception is raised and the iterator will\n      have reached the end of the set of values to be 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 function\'s\n      name; "__self__" is set to "None" (but see the next item);\n      "__module__" is the name of the module the function was defined\n      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   Class Types\n      Class types, or "new-style classes," are callable.  These\n      objects normally act as factories for new instances of\n      themselves, but variations are possible for class types that\n      override "__new__()".  The arguments of the call are passed to\n      "__new__()" and, in the typical case, to "__init__()" to\n      initialize the new instance.\n\n   Classic Classes\n      Class objects are described below.  When a class object is\n      called, a new class instance (also described below) is created\n      and returned.  This implies a call to the class\'s "__init__()"\n      method if it has one.  Any arguments are passed on to the\n      "__init__()" method.  If there is no "__init__()" method, the\n      class must be called without arguments.\n\n   Class instances\n      Class instances are described below.  Class instances are\n      callable only when the class has a "__call__()" method;\n      "x(arguments)" is a shorthand for "x.__call__(arguments)".\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   func_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 name;\n   "__doc__" is the module\'s documentation string, or "None" if\n   unavailable; "__file__" is the pathname of the file from which the\n   module was loaded, if it was loaded from a file. The "__file__"\n   attribute is not present for C modules that are statically linked\n   into the interpreter; for extension modules loaded dynamically from\n   a shared library, it is the pathname of the shared library file.\n\nClasses\n   Both class types (new-style classes) and class objects (old-\n   style/classic classes) are typically created by class definitions\n   (see section *Class definitions*).  A class has a namespace\n   implemented by a dictionary object. Class attribute references are\n   translated to lookups in this dictionary, e.g., "C.x" is translated\n   to "C.__dict__["x"]" (although for new-style classes in particular\n   there are a number of hooks which allow for other means of locating\n   attributes). When the attribute name is not found there, the\n   attribute search continues in the base classes.  For old-style\n   classes, the search is depth-first, left-to-right in the order of\n   occurrence in the base class list. New-style classes use the more\n   complex C3 method resolution order which behaves correctly even in\n   the presence of \'diamond\' inheritance structures where there are\n   multiple inheritance paths leading back to a common ancestor.\n   Additional details on the C3 MRO used by new-style classes can be\n   found in the documentation accompanying the 2.3 release at\n   https://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class "C", say) would yield a\n   user-defined function object or an unbound user-defined method\n   object whose associated class is either "C" or one of its base\n   classes, it is transformed into an unbound user-defined method\n   object whose "im_class" attribute is "C". When it would yield a\n   class method object, it is transformed into a bound user-defined\n   method object whose "im_self" attribute is "C".  When it would\n   yield a static method object, it is transformed into the object\n   wrapped by the static method object. See section *Implementing\n   Descriptors* for another way in which attributes retrieved from a\n   class may differ from those actually contained in its "__dict__"\n   (note that only new-style classes support descriptors).\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__" is\n   the module name in which the class was defined; "__dict__" is the\n   dictionary containing the class\'s namespace; "__bases__" is a tuple\n   (possibly empty or a singleton) containing the base classes, in the\n   order of their occurrence in the base class list; "__doc__" is the\n   class\'s documentation string, or None if 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 or an unbound user-defined method object whose\n   associated class is the class (call it "C") of the instance for\n   which the attribute reference was initiated or one of its bases, it\n   is transformed into a bound user-defined method object whose\n   "im_class" attribute is "C" and whose "im_self" attribute is the\n   instance. Static method and class method objects are also\n   transformed, as if they had been retrieved from class "C"; see\n   above under "Classes". See section *Implementing Descriptors* for\n   another way in which attributes of a class retrieved via its\n   instances may differ from the objects actually stored in the\n   class\'s "__dict__". If no class attribute is found, and the\n   object\'s class has a "__getattr__()" method, that is called to\n   satisfy the 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 instead\n   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\nFiles\n   A file object represents an open file.  File objects are created by\n   the "open()" built-in function, and also by "os.popen()",\n   "os.fdopen()", and the "makefile()" method of socket objects (and\n   perhaps by other functions or methods provided by extension\n   modules).  The objects "sys.stdin", "sys.stdout" and "sys.stderr"\n   are initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams.  See *File Objects* for\n   complete documentation of file objects.\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 name;\n      "co_argcount" is the number of positional arguments (including\n      arguments with default values); "co_nlocals" is the number of\n      local variables used by the function (including arguments);\n      "co_varnames" is a tuple containing the names of the local\n      variables (starting with the argument names); "co_cellvars" is a\n      tuple containing the names of local variables that are\n      referenced by nested functions; "co_freevars" is a tuple\n      containing the names of free variables; "co_code" is a string\n      representing the sequence of bytecode instructions; "co_consts"\n      is a tuple containing the literals used by the bytecode;\n      "co_names" is a tuple containing the names used by the bytecode;\n      "co_filename" is 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 a\n      number of flags for the interpreter.\n\n      The following flag bits are defined for "co_flags": bit "0x04"\n      is set if the function uses the "*arguments" syntax to accept an\n      arbitrary number of positional arguments; bit "0x08" is set if\n      the function uses the "**keywords" syntax to accept arbitrary\n      keyword arguments; bit "0x20" is set if the function is a\n      generator.\n\n      Future feature declarations ("from __future__ import division")\n      also use bits in "co_flags" to indicate whether a code object\n      was compiled with a particular feature enabled: bit "0x2000" is\n      set if the function was compiled with future division enabled;\n      bits "0x10" and "0x1000" were used in earlier versions of\n      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 stack\n      frame (towards the caller), or "None" if this is the bottom\n      stack frame; "f_code" is the code object being executed in this\n      frame; "f_locals" is the dictionary used to look up local\n      variables; "f_globals" is used for global variables;\n      "f_builtins" is used for built-in (intrinsic) names;\n      "f_restricted" is a flag indicating whether the function is\n      executing in restricted execution mode; "f_lasti" gives the\n      precise instruction (this is an index into the bytecode string\n      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_exc_type", "f_exc_value",\n      "f_exc_traceback" represent the last exception raised in the\n      parent frame provided another exception was ever raised in the\n      current frame (in all other cases they are None); "f_lineno" is\n      the current line number of the frame --- writing to this from\n      within a trace function jumps to the given line (only for the\n      bottom-most frame).  A debugger can implement a Jump command\n      (aka Set Next Statement) 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 "sys.exc_traceback",\n      and also as the third item of the tuple returned by\n      "sys.exc_info()".  The latter is the preferred interface, since\n      it works correctly when the program is using multiple threads.\n      When the program contains no suitable handler, the stack trace\n      is written (nicely formatted) to the standard error stream; if\n      the interpreter is interactive, it is also made available to the\n      user as "sys.last_traceback".\n\n      Special read-only attributes: "tb_next" is the next level in the\n      stack trace (towards the frame where the exception occurred), or\n      "None" if there is no next level; "tb_frame" points to the\n      execution frame of the current level; "tb_lineno" gives the line\n      number where the exception occurred; "tb_lasti" indicates the\n      precise instruction.  The line number and last instruction in\n      the traceback may differ from the line number of its frame\n      object if the exception occurred in a "try" statement with no\n      matching except clause or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices when *extended slice\n      syntax* is used. This is a slice using two colons, or multiple\n      slices or ellipses separated by commas, e.g., "a[i:j:step]",\n      "a[i:j, k:l]", or "a[..., i:j]".  They are also created by the\n      built-in "slice()" function.\n\n      Special read-only attributes: "start" is the lower bound; "stop"\n      is the upper bound; "step" is the step value; each is "None" if\n      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 extended slice that the slice\n         object would describe if applied to a sequence of *length*\n         items.  It returns a tuple of three integers; respectively\n         these are the *start* and *stop* indices and the *step* or\n         stride length of the slice. Missing or out-of-bounds indices\n         are handled in a manner consistent with regular slices.\n\n         New in version 2.3.\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': u'\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': u'\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" module.)\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 index\nthe same dictionary entry.  (Note however, that since computers store\nfloating-point numbers as approximations it is usually unwise to use\nthem as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of "key:\nvalue" pairs within braces, for example: "{\'jack\': 4098, \'sjoerd\':\n4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the "dict"\nconstructor.\n\nclass class dict(**kwarg)\nclass class dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n   Return a new dictionary initialized from an optional positional\n   argument and a possibly empty set of keyword arguments.\n\n   If no positional argument is given, an empty dictionary is created.\n   If a positional argument is given and it is a mapping object, a\n   dictionary is created with the same key-value pairs as the mapping\n   object.  Otherwise, the positional argument must be an *iterable*\n   object.  Each item in the iterable must itself be an iterable with\n   exactly two objects.  The first object of each item becomes a key\n   in the new dictionary, and the second object the corresponding\n   value.  If a key occurs more than once, the last value for that key\n   becomes the corresponding value in the new dictionary.\n\n   If keyword arguments are given, the keyword arguments and their\n   values are added to the dictionary created from the positional\n   argument.  If a key being added is already present, the value from\n   the keyword argument replaces the value from the positional\n   argument.\n\n   To illustrate, the following examples all return a dictionary equal\n   to "{"one": 1, "two": 2, "three": 3}":\n\n      >>> a = dict(one=1, two=2, three=3)\n      >>> b = {\'one\': 1, \'two\': 2, \'three\': 3}\n      >>> c = dict(zip([\'one\', \'two\', \'three\'], [1, 2, 3]))\n      >>> d = dict([(\'two\', 2), (\'one\', 1), (\'three\', 3)])\n      >>> e = dict({\'three\': 3, \'one\': 1, \'two\': 2})\n      >>> a == b == c == d == e\n      True\n\n   Providing keyword arguments as in the first example only works for\n   keys that are valid Python identifiers.  Otherwise, any valid keys\n   can be used.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for building a dictionary from\n   keyword arguments added.\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      New in version 2.5: If a subclass of dict defines a method\n      "__missing__()", if the key *key* is not present, the "d[key]"\n      operation calls that method with the key *key* as argument.  The\n      "d[key]" operation then returns or raises whatever is returned\n      or raised by the "__missing__(key)" call if the key is not\n      present. No other operations or methods invoke "__missing__()".\n      If "__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 not\n      in the map.\n\n   key in d\n\n      Return "True" if *d* has a key *key*, else "False".\n\n      New in version 2.2.\n\n   key not in d\n\n      Equivalent to "not key in d".\n\n      New in version 2.2.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for "iterkeys()".\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   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      New in version 2.3.\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", so\n      that this method never raises a "KeyError".\n\n   has_key(key)\n\n      Test for the presence of *key* in the dictionary.  "has_key()"\n      is deprecated in favor of "key in d".\n\n   items()\n\n      Return a copy of the dictionary\'s list of "(key, value)" pairs.\n\n      **CPython implementation detail:** Keys and values are listed in\n      an arbitrary order which is non-random, varies across Python\n      implementations, and depends on the dictionary\'s history of\n      insertions and deletions.\n\n      If "items()", "keys()", "values()", "iteritems()", "iterkeys()",\n      and "itervalues()" are called with no intervening modifications\n      to the dictionary, the lists will directly correspond.  This\n      allows the creation of "(value, key)" pairs using "zip()":\n      "pairs = zip(d.values(), d.keys())".  The same relationship\n      holds for the "iterkeys()" and "itervalues()" methods: "pairs =\n      zip(d.itervalues(), d.iterkeys())" provides the same value for\n      "pairs". Another way to create the same list is "pairs = [(v, k)\n      for (k, v) in d.iteritems()]".\n\n   iteritems()\n\n      Return an iterator over the dictionary\'s "(key, value)" pairs.\n      See the note for "dict.items()".\n\n      Using "iteritems()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   iterkeys()\n\n      Return an iterator over the dictionary\'s keys.  See the note for\n      "dict.items()".\n\n      Using "iterkeys()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   itervalues()\n\n      Return an iterator over the dictionary\'s values.  See the note\n      for "dict.items()".\n\n      Using "itervalues()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   keys()\n\n      Return a copy of the dictionary\'s list of keys.  See the note\n      for "dict.items()".\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      New in version 2.3.\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      Changed in version 2.4: Allowed the argument to be an iterable\n      of key/value pairs and allowed keyword arguments.\n\n   values()\n\n      Return a copy of the dictionary\'s list of values.  See the note\n      for "dict.items()".\n\n   viewitems()\n\n      Return a new view of the dictionary\'s items ("(key, value)"\n      pairs).  See below for documentation of view objects.\n\n      New in version 2.7.\n\n   viewkeys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n      New in version 2.7.\n\n   viewvalues()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n      New in version 2.7.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by "dict.viewkeys()", "dict.viewvalues()" and\n"dict.viewitems()" 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 using\n   "zip()": "pairs = zip(d.values(), d.keys())".  Another way to\n   create the same list is "pairs = [(v, k) for (k, v) in 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, values\n   or items (in the latter case, *x* should be a "(key, value)"\n   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\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.viewkeys()\n   >>> values = dishes.viewvalues()\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',
- 'typesmethods': u'\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as "append()" on lists)\nand class instance methods.  Built-in methods are described with the\ntypes that support them.\n\nThe implementation adds two special read-only attributes to class\ninstance methods: "m.im_self" is the object on which the method\noperates, and "m.im_func" is the function implementing the method.\nCalling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to\ncalling "m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)".\n\nClass instance methods are either *bound* or *unbound*, referring to\nwhether the method was accessed through an instance or a class,\nrespectively.  When a method is unbound, its "im_self" attribute will\nbe "None" and if called, an explicit "self" object must be passed as\nthe first argument.  In this case, "self" must be an instance of the\nunbound method\'s class (or a subclass of that class), otherwise a\n"TypeError" is raised.\n\nLike function objects, methods objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object ("meth.im_func"), setting method\nattributes on either bound or unbound methods is disallowed.\nAttempting to set an attribute on a method results in an\n"AttributeError" being raised.  In order to set a method attribute,\nyou need to explicitly set it on the underlying function object:\n\n   >>> class C:\n   ...     def method(self):\n   ...         pass\n   ...\n   >>> c = C()\n   >>> c.method.whoami = \'my name is method\'  # can\'t set on the method\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   AttributeError: \'instancemethod\' object has no attribute \'whoami\'\n   >>> c.method.im_func.whoami = \'my name is method\'\n   >>> c.method.whoami\n   \'my name is method\'\n\nSee *The standard type hierarchy* for more information.\n',
+ 'try': u'\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" | ",") identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n"try"..."except"..."finally" did not work. "try"..."except" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified in that except clause, if present, and the except\nclause\'s suite is executed.  All except clauses must have an\nexecutable block.  When the end of this block is reached, execution\ncontinues normally after the entire try statement.  (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the "sys" module:\n"sys.exc_type" receives the object identifying the exception;\n"sys.exc_value" receives the exception\'s parameter;\n"sys.exc_traceback" receives a traceback object (see section The\nstandard type hierarchy) identifying the point in the program where\nthe exception occurred. These details are also available through the\n"sys.exc_info()" function, which returns a tuple "(exc_type,\nexc_value, exc_traceback)".  Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program.  As of Python 1.5, the variables 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\n\nAdditional information on exceptions can be found in section\nExceptions, and information on using the "raise" statement to generate\nexceptions may be found in section The raise statement.\n',
+ 'types': u'\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.).\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". It\n   is used to signify the absence of a value in many situations, e.g.,\n   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 built-in name\n   "Ellipsis". It is used to indicate the presence of the "..." syntax\n   in a slice.  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 three types of integers:\n\n      Plain integers\n         These represent numbers in the range -2147483648 through\n         2147483647. (The range may be larger on machines with a\n         larger natural word size, but not smaller.)  When the result\n         of an operation would fall outside this range, the result is\n         normally returned as a long integer (in some cases, the\n         exception "OverflowError" is raised instead).  For the\n         purpose of shift and mask operations, integers are assumed to\n         have a binary, 2\'s complement notation using 32 or more bits,\n         and hiding no bits from the user (i.e., all 4294967296\n         different bit patterns correspond to different values).\n\n      Long integers\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\n         These represent the truth values False and True.  The two\n         objects representing the values "False" and "True" are the\n         only Boolean objects. The Boolean type is a subtype of plain\n         integers, 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 and the least surprises when\n      switching between the plain and long integer domains.  Any\n      operation, if it yields a result in the plain integer domain,\n      will yield the same result in the long integer domain or when\n      using mixed operands.  The switch between domains is transparent\n      to the programmer.\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 are\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"\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 items\n   of a sequence. When the length of a sequence is *n*, the index set\n   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is\n   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* where\n   "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *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 are characters.  There is no separate\n         character type; a character is represented by a string of one\n         item. Characters represent (at least) 8-bit bytes.  The\n         built-in functions "chr()" and "ord()" convert between\n         characters and nonnegative integers representing the byte\n         values.  Bytes with the values 0-127 usually represent the\n         corresponding ASCII values, but the interpretation of values\n         is up to the program.  The string data type is also used to\n         represent arrays of bytes, e.g., to hold data read from a\n         file.\n\n         (On systems whose native character set is not ASCII, strings\n         may use EBCDIC in their internal representation, provided the\n         functions "chr()" and "ord()" implement a mapping between\n         ASCII and EBCDIC, and string comparison preserves the ASCII\n         order. Or perhaps someone can propose a better rule?)\n\n      Unicode\n         The items of a Unicode object are Unicode code units.  A\n         Unicode code unit is represented by a Unicode 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 "unichr()" 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 Unicode method "encode()" and the built-\n         in function "unicode()".\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   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 a\n      mutable sequence type.\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 immutable\n      and *hashable*, it can be used again as an element of another\n      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 "k"\n   from the mapping "a"; this can be used in expressions and as the\n   target of assignments or "del" statements. The built-in function\n   "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 "1.0")\n      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", "gdbm", and "bsddb" provide\n      additional examples of mapping types.\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__" "func_doc"    | The function\'s documentation    | Writable    |\n      |                         | string, or "None" if            |             |\n      |                         | unavailable.                    |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__name__" "func_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      | "func_defaults"         | argument values for those       |             |\n      |                         | arguments that have defaults,   |             |\n      |                         | or "None" if no arguments have  |             |\n      |                         | a default value.                |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__code__" "func_code"  | The code object representing    | Writable    |\n      |                         | the compiled function body.     |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__globals__"           | A reference to the dictionary   | Read-only   |\n      | "func_globals"          | 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__" "func_dict"  | The namespace supporting        | Writable    |\n      |                         | arbitrary function attributes.  |             |\n      +-------------------------+---------------------------------+-------------+\n      | "__closure__"           | "None" or a tuple of cells that | Read-only   |\n      | "func_closure"          | contain bindings for the        |             |\n      |                         | function\'s free variables.      |             |\n      +-------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Changed in version 2.4: "func_name" is now writable.\n\n      Changed in version 2.6: The double-underscore attributes\n      "__closure__", "__code__", "__defaults__", and "__globals__"\n      were introduced as aliases for the corresponding "func_*"\n      attributes for forwards compatibility with Python 3.\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   User-defined methods\n      A user-defined method object combines a class, a class instance\n      (or "None") and any callable object (normally a user-defined\n      function).\n\n      Special read-only attributes: "im_self" is the class instance\n      object, "im_func" is the function object; "im_class" is the\n      class of "im_self" for bound methods or the class that asked for\n      the method for unbound methods; "__doc__" is the method\'s\n      documentation (same as "im_func.__doc__"); "__name__" is the\n      method name (same as "im_func.__name__"); "__module__" is the\n      name of the module the method was defined in, or "None" if\n      unavailable.\n\n      Changed in version 2.2: "im_self" used to refer to the class\n      that defined the method.\n\n      Changed in version 2.6: For Python 3 forward-compatibility,\n      "im_func" is also available as "__func__", and "im_self" as\n      "__self__".\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, an unbound\n      user-defined method object, or a class method object. When the\n      attribute is a user-defined method object, a new method object\n      is only created if the class from which it is being retrieved is\n      the same as, or a derived class of, the class stored in the\n      original method object; otherwise, the original method object is\n      used as it is.\n\n      When a user-defined method object is created by retrieving a\n      user-defined function object from a class, its "im_self"\n      attribute is "None" and the method object is said to be unbound.\n      When one is created by retrieving a user-defined function object\n      from a class via one of its instances, its "im_self" attribute\n      is the instance, and the method object is said to be bound. In\n      either case, the new method\'s "im_class" attribute is the class\n      from which the retrieval takes place, and its "im_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 "im_func"\n      attribute of the new instance is not the original method object\n      but its "im_func" attribute.\n\n      When a user-defined method object is created by retrieving a\n      class method object from a class or instance, its "im_self"\n      attribute is the class itself, and its "im_func" attribute is\n      the function object underlying the class method.\n\n      When an unbound user-defined method object is called, the\n      underlying function ("im_func") is called, with the restriction\n      that the first argument must be an instance of the proper class\n      ("im_class") or of a derived class thereof.\n\n      When a bound user-defined method object is called, the\n      underlying function ("im_func") is called, inserting the class\n      instance ("im_self") in front of the argument list.  For\n      instance, when "C" is a class which contains a definition for a\n      function "f()", and "x" is an instance of "C", calling "x.f(1)"\n      is equivalent to calling "C.f(x, 1)".\n\n      When a user-defined method object is derived from a class method\n      object, the "class instance" stored in "im_self" will actually\n      be the class itself, so that calling either "x.f(1)" or "C.f(1)"\n      is equivalent to calling "f(C,1)" where "f" is the underlying\n      function.\n\n      Note that the transformation from function object to (unbound or\n      bound) method object happens each time the attribute is\n      retrieved from the class or instance. In some cases, a fruitful\n      optimization is to assign the attribute to a local variable and\n      call that local variable. Also notice that this transformation\n      only happens for user-defined functions; other callable objects\n      (and all non-callable objects) are retrieved without\n      transformation.  It is also important to note that user-defined\n      functions which are attributes of a class instance are not\n      converted to bound methods; this *only* happens when the\n      function is an attribute 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 the\n      end, a "StopIteration" exception is raised and the iterator will\n      have reached the end of the set of values to be 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 function\'s\n      name; "__self__" is set to "None" (but see the next item);\n      "__module__" is the name of the module the function was defined\n      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   Class Types\n      Class types, or "new-style classes," are callable.  These\n      objects normally act as factories for new instances of\n      themselves, but variations are possible for class types that\n      override "__new__()".  The arguments of the call are passed to\n      "__new__()" and, in the typical case, to "__init__()" to\n      initialize the new instance.\n\n   Classic Classes\n      Class objects are described below.  When a class object is\n      called, a new class instance (also described below) is created\n      and returned.  This implies a call to the class\'s "__init__()"\n      method if it has one.  Any arguments are passed on to the\n      "__init__()" method.  If there is no "__init__()" method, the\n      class must be called without arguments.\n\n   Class instances\n      Class instances are described below.  Class instances are\n      callable only when the class has a "__call__()" method;\n      "x(arguments)" is a shorthand for "x.__call__(arguments)".\n\nModules\n   Modules are imported by the "import" statement (see section The\n   import statement). A module object has a namespace implemented by a\n   dictionary object (this is the dictionary referenced by the\n   func_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 name;\n   "__doc__" is the module\'s documentation string, or "None" if\n   unavailable; "__file__" is the pathname of the file from which the\n   module was loaded, if it was loaded from a file. The "__file__"\n   attribute is not present for C modules that are statically linked\n   into the interpreter; for extension modules loaded dynamically from\n   a shared library, it is the pathname of the shared library file.\n\nClasses\n   Both class types (new-style classes) and class objects (old-\n   style/classic classes) are typically created by class definitions\n   (see section Class definitions).  A class has a namespace\n   implemented by a dictionary object. Class attribute references are\n   translated to lookups in this dictionary, e.g., "C.x" is translated\n   to "C.__dict__["x"]" (although for new-style classes in particular\n   there are a number of hooks which allow for other means of locating\n   attributes). When the attribute name is not found there, the\n   attribute search continues in the base classes.  For old-style\n   classes, the search is depth-first, left-to-right in the order of\n   occurrence in the base class list. New-style classes use the more\n   complex C3 method resolution order which behaves correctly even in\n   the presence of \'diamond\' inheritance structures where there are\n   multiple inheritance paths leading back to a common ancestor.\n   Additional details on the C3 MRO used by new-style classes can be\n   found in the documentation accompanying the 2.3 release at\n   https://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class "C", say) would yield a\n   user-defined function object or an unbound user-defined method\n   object whose associated class is either "C" or one of its base\n   classes, it is transformed into an unbound user-defined method\n   object whose "im_class" attribute is "C". When it would yield a\n   class method object, it is transformed into a bound user-defined\n   method object whose "im_self" attribute is "C".  When it would\n   yield a static method object, it is transformed into the object\n   wrapped by the static method object. See section Implementing\n   Descriptors for another way in which attributes retrieved from a\n   class may differ from those actually contained in its "__dict__"\n   (note that only new-style classes support descriptors).\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__" is\n   the module name in which the class was defined; "__dict__" is the\n   dictionary containing the class\'s namespace; "__bases__" is a tuple\n   (possibly empty or a singleton) containing the base classes, in the\n   order of their occurrence in the base class list; "__doc__" is the\n   class\'s documentation string, or None if 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 or an unbound user-defined method object whose\n   associated class is the class (call it "C") of the instance for\n   which the attribute reference was initiated or one of its bases, it\n   is transformed into a bound user-defined method object whose\n   "im_class" attribute is "C" and whose "im_self" attribute is the\n   instance. Static method and class method objects are also\n   transformed, as if they had been retrieved from class "C"; see\n   above under "Classes". See section Implementing Descriptors for\n   another way in which attributes of a class retrieved via its\n   instances may differ from the objects actually stored in the\n   class\'s "__dict__". If no class attribute is found, and the\n   object\'s class has a "__getattr__()" method, that is called to\n   satisfy the 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 instead\n   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\nFiles\n   A file object represents an open file.  File objects are created by\n   the "open()" built-in function, and also by "os.popen()",\n   "os.fdopen()", and the "makefile()" method of socket objects (and\n   perhaps by other functions or methods provided by extension\n   modules).  The objects "sys.stdin", "sys.stdout" and "sys.stderr"\n   are initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams.  See File Objects for\n   complete documentation of file objects.\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 name;\n      "co_argcount" is the number of positional arguments (including\n      arguments with default values); "co_nlocals" is the number of\n      local variables used by the function (including arguments);\n      "co_varnames" is a tuple containing the names of the local\n      variables (starting with the argument names); "co_cellvars" is a\n      tuple containing the names of local variables that are\n      referenced by nested functions; "co_freevars" is a tuple\n      containing the names of free variables; "co_code" is a string\n      representing the sequence of bytecode instructions; "co_consts"\n      is a tuple containing the literals used by the bytecode;\n      "co_names" is a tuple containing the names used by the bytecode;\n      "co_filename" is 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 a\n      number of flags for the interpreter.\n\n      The following flag bits are defined for "co_flags": bit "0x04"\n      is set if the function uses the "*arguments" syntax to accept an\n      arbitrary number of positional arguments; bit "0x08" is set if\n      the function uses the "**keywords" syntax to accept arbitrary\n      keyword arguments; bit "0x20" is set if the function is a\n      generator.\n\n      Future feature declarations ("from __future__ import division")\n      also use bits in "co_flags" to indicate whether a code object\n      was compiled with a particular feature enabled: bit "0x2000" is\n      set if the function was compiled with future division enabled;\n      bits "0x10" and "0x1000" were used in earlier versions of\n      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 stack\n      frame (towards the caller), or "None" if this is the bottom\n      stack frame; "f_code" is the code object being executed in this\n      frame; "f_locals" is the dictionary used to look up local\n      variables; "f_globals" is used for global variables;\n      "f_builtins" is used for built-in (intrinsic) names;\n      "f_restricted" is a flag indicating whether the function is\n      executing in restricted execution mode; "f_lasti" gives the\n      precise instruction (this is an index into the bytecode string\n      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_exc_type", "f_exc_value",\n      "f_exc_traceback" represent the last exception raised in the\n      parent frame provided another exception was ever raised in the\n      current frame (in all other cases they are None); "f_lineno" is\n      the current line number of the frame --- writing to this from\n      within a trace function jumps to the given line (only for the\n      bottom-most frame).  A debugger can implement a Jump command\n      (aka Set Next Statement) 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 "sys.exc_traceback", and\n      also as the third item of the tuple returned by\n      "sys.exc_info()".  The latter is the preferred interface, since\n      it works correctly when the program is using multiple threads.\n      When the program contains no suitable handler, the stack trace\n      is written (nicely formatted) to the standard error stream; if\n      the interpreter is interactive, it is also made available to the\n      user as "sys.last_traceback".\n\n      Special read-only attributes: "tb_next" is the next level in the\n      stack trace (towards the frame where the exception occurred), or\n      "None" if there is no next level; "tb_frame" points to the\n      execution frame of the current level; "tb_lineno" gives the line\n      number where the exception occurred; "tb_lasti" indicates the\n      precise instruction.  The line number and last instruction in\n      the traceback may differ from the line number of its frame\n      object if the exception occurred in a "try" statement with no\n      matching except clause or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices when *extended slice\n      syntax* is used. This is a slice using two colons, or multiple\n      slices or ellipses separated by commas, e.g., "a[i:j:step]",\n      "a[i:j, k:l]", or "a[..., i:j]".  They are also created by the\n      built-in "slice()" function.\n\n      Special read-only attributes: "start" is the lower bound; "stop"\n      is the upper bound; "step" is the step value; each is "None" if\n      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 extended slice that the slice\n         object would describe if applied to a sequence of *length*\n         items.  It returns a tuple of three integers; respectively\n         these are the *start* and *stop* indices and the *step* or\n         stride length of the slice. Missing or out-of-bounds indices\n         are handled in a manner consistent with regular slices.\n\n         New in version 2.3.\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': u'\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': u'\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" module.)\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 index\nthe same dictionary entry.  (Note however, that since computers store\nfloating-point numbers as approximations it is usually unwise to use\nthem as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of "key:\nvalue" pairs within braces, for example: "{\'jack\': 4098, \'sjoerd\':\n4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the "dict"\nconstructor.\n\nclass class dict(**kwarg)\nclass class dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n   Return a new dictionary initialized from an optional positional\n   argument and a possibly empty set of keyword arguments.\n\n   If no positional argument is given, an empty dictionary is created.\n   If a positional argument is given and it is a mapping object, a\n   dictionary is created with the same key-value pairs as the mapping\n   object.  Otherwise, the positional argument must be an *iterable*\n   object.  Each item in the iterable must itself be an iterable with\n   exactly two objects.  The first object of each item becomes a key\n   in the new dictionary, and the second object the corresponding\n   value.  If a key occurs more than once, the last value for that key\n   becomes the corresponding value in the new dictionary.\n\n   If keyword arguments are given, the keyword arguments and their\n   values are added to the dictionary created from the positional\n   argument.  If a key being added is already present, the value from\n   the keyword argument replaces the value from the positional\n   argument.\n\n   To illustrate, the following examples all return a dictionary equal\n   to "{"one": 1, "two": 2, "three": 3}":\n\n      >>> a = dict(one=1, two=2, three=3)\n      >>> b = {\'one\': 1, \'two\': 2, \'three\': 3}\n      >>> c = dict(zip([\'one\', \'two\', \'three\'], [1, 2, 3]))\n      >>> d = dict([(\'two\', 2), (\'one\', 1), (\'three\', 3)])\n      >>> e = dict({\'three\': 3, \'one\': 1, \'two\': 2})\n      >>> a == b == c == d == e\n      True\n\n   Providing keyword arguments as in the first example only works for\n   keys that are valid Python identifiers.  Otherwise, any valid keys\n   can be used.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for building a dictionary from\n   keyword arguments added.\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__()" and *key*\n      is not present, the "d[key]" operation calls that method with\n      the key *key* as argument.  The "d[key]" operation then returns\n      or raises whatever is returned or raised by the\n      "__missing__(key)" call. No other operations or methods invoke\n      "__missing__()". If "__missing__()" is not defined, "KeyError"\n      is raised. "__missing__()" must be a method; it cannot be an\n      instance 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      The example above shows part of the implementation of\n      "collections.Counter".  A different "__missing__" method is used\n      by "collections.defaultdict".\n\n      New in version 2.5: Recognition of __missing__ methods of dict\n      subclasses.\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 not\n      in the map.\n\n   key in d\n\n      Return "True" if *d* has a key *key*, else "False".\n\n      New in version 2.2.\n\n   key not in d\n\n      Equivalent to "not key in d".\n\n      New in version 2.2.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for "iterkeys()".\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   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      New in version 2.3.\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", so\n      that this method never raises a "KeyError".\n\n   has_key(key)\n\n      Test for the presence of *key* in the dictionary.  "has_key()"\n      is deprecated in favor of "key in d".\n\n   items()\n\n      Return a copy of the dictionary\'s list of "(key, value)" pairs.\n\n      **CPython implementation detail:** Keys and values are listed in\n      an arbitrary order which is non-random, varies across Python\n      implementations, and depends on the dictionary\'s history of\n      insertions and deletions.\n\n      If "items()", "keys()", "values()", "iteritems()", "iterkeys()",\n      and "itervalues()" are called with no intervening modifications\n      to the dictionary, the lists will directly correspond.  This\n      allows the creation of "(value, key)" pairs using "zip()":\n      "pairs = zip(d.values(), d.keys())".  The same relationship\n      holds for the "iterkeys()" and "itervalues()" methods: "pairs =\n      zip(d.itervalues(), d.iterkeys())" provides the same value for\n      "pairs". Another way to create the same list is "pairs = [(v, k)\n      for (k, v) in d.iteritems()]".\n\n   iteritems()\n\n      Return an iterator over the dictionary\'s "(key, value)" pairs.\n      See the note for "dict.items()".\n\n      Using "iteritems()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   iterkeys()\n\n      Return an iterator over the dictionary\'s keys.  See the note for\n      "dict.items()".\n\n      Using "iterkeys()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   itervalues()\n\n      Return an iterator over the dictionary\'s values.  See the note\n      for "dict.items()".\n\n      Using "itervalues()" while adding or deleting entries in the\n      dictionary may raise a "RuntimeError" or fail to iterate over\n      all entries.\n\n      New in version 2.2.\n\n   keys()\n\n      Return a copy of the dictionary\'s list of keys.  See the note\n      for "dict.items()".\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      New in version 2.3.\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      Changed in version 2.4: Allowed the argument to be an iterable\n      of key/value pairs and allowed keyword arguments.\n\n   values()\n\n      Return a copy of the dictionary\'s list of values.  See the note\n      for "dict.items()".\n\n   viewitems()\n\n      Return a new view of the dictionary\'s items ("(key, value)"\n      pairs).  See below for documentation of view objects.\n\n      New in version 2.7.\n\n   viewkeys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n      New in version 2.7.\n\n   viewvalues()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n      New in version 2.7.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by "dict.viewkeys()", "dict.viewvalues()" and\n"dict.viewitems()" 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 using\n   "zip()": "pairs = zip(d.values(), d.keys())".  Another way to\n   create the same list is "pairs = [(v, k) for (k, v) in 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, values\n   or items (in the latter case, *x* should be a "(key, value)"\n   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\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.viewkeys()\n   >>> values = dishes.viewvalues()\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',
+ 'typesmethods': u'\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as "append()" on lists)\nand class instance methods.  Built-in methods are described with the\ntypes that support them.\n\nThe implementation adds two special read-only attributes to class\ninstance methods: "m.im_self" is the object on which the method\noperates, and "m.im_func" is the function implementing the method.\nCalling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to\ncalling "m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)".\n\nClass instance methods are either *bound* or *unbound*, referring to\nwhether the method was accessed through an instance or a class,\nrespectively.  When a method is unbound, its "im_self" attribute will\nbe "None" and if called, an explicit "self" object must be passed as\nthe first argument.  In this case, "self" must be an instance of the\nunbound method\'s class (or a subclass of that class), otherwise a\n"TypeError" is raised.\n\nLike function objects, methods objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object ("meth.im_func"), setting method\nattributes on either bound or unbound methods is disallowed.\nAttempting to set an attribute on a method results in an\n"AttributeError" being raised.  In order to set a method attribute,\nyou need to explicitly set it on the underlying function object:\n\n   >>> class C:\n   ...     def method(self):\n   ...         pass\n   ...\n   >>> c = C()\n   >>> c.method.whoami = \'my name is method\'  # can\'t set on the method\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   AttributeError: \'instancemethod\' object has no attribute \'whoami\'\n   >>> c.method.im_func.whoami = \'my name is method\'\n   >>> c.method.whoami\n   \'my name is method\'\n\nSee The standard type hierarchy for more information.\n',
  'typesmodules': u'\nModules\n*******\n\nThe only special operation on a module is attribute access: "m.name",\nwhere *m* is a module and *name* accesses a name defined in *m*\'s\nsymbol table. Module attributes can be assigned to.  (Note that the\n"import" statement is not, strictly speaking, an operation on a module\nobject; "import foo" does not require a module object named *foo* to\nexist, rather it requires an (external) *definition* for a module\nnamed *foo* somewhere.)\n\nA special attribute 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 write\n"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but you can\'t\nwrite "m.__dict__ = {}").  Modifying "__dict__" directly is not\nrecommended.\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': u'\nSequence Types --- "str", "unicode", "list", "tuple", "bytearray", "buffer", "xrange"\n*************************************************************************************\n\nThere are seven sequence types: strings, Unicode strings, lists,\ntuples, bytearrays, buffers, and xrange objects.\n\nFor other containers see the built in "dict" and "set" classes, and\nthe "collections" module.\n\nString literals are written in single or double quotes: "\'xyzzy\'",\n""frobozz"".  See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding "\'u\'" character: "u\'abc\'", "u"def"". In addition to\nthe functionality described here, there are also string-specific\nmethods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: "[a,\nb, c]". Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as "a, b, c" or "()".\nA single item tuple must have a trailing comma, such as "(d,)".\n\nBytearray objects are created with the built-in function\n"bytearray()".\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function "buffer()".  They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n"xrange()" function.  They don\'t support slicing, concatenation or\nrepetition, and using "in", "not in", "min()" or "max()" on them is\ninefficient.\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 the\ncorresponding numeric operations. [3] Additional methods are provided\nfor *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority.\nIn the table, *s* and *t* are sequences of the same type; *n*, *i* and\n*j* are integers:\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(x)"       | index of the first occurrence of |            |\n|                    | *x* in *s*                       |            |\n+--------------------+----------------------------------+------------+\n| "s.count(x)"       | total number of occurrences of   |            |\n|                    | *x* 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 compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the "in" and "not\n   in" operations act like a substring test.  In Python versions\n   before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n   beyond, *x* may be a string of any length.\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\n   the 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 "None",\n   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* is\n   greater than or equal to *j*, the slice is 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", "i+2*k",\n   "i+3*k" and so on, stopping when *j* is reached (but never\n   including *j*).  If *i* or *j* is greater than "len(s)", use\n   "len(s)".  If *i* or *j* are omitted or "None", they become "end"\n   values (which end depends on the sign of *k*).  Note, *k* cannot be\n   zero. If *k* is "None", it is treated like "1".\n\n6. **CPython implementation detail:** If *s* and *t* are both\n   strings, some Python implementations such as CPython can usually\n   perform an in-place optimization for assignments of the form "s = s\n   + t" or "s += t".  When applicable, this optimization makes\n   quadratic run-time much less likely.  This optimization is both\n   version and implementation dependent.  For performance sensitive\n   code, it is preferable to use the "str.join()" method which assures\n   consistent linear concatenation performance across versions and\n   implementations.\n\n   Changed in version 2.4: Formerly, string concatenation never\n   occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.  Some of them are also available on\n"bytearray" objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the "%" operator described in the *String\nFormatting Operations* section. Also, see the "re" module for string\nfunctions based 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\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n   Decodes the string using the codec registered for *encoding*.\n   *encoding* defaults to the default string encoding.  *errors* may\n   be given to set a different error handling scheme.  The default is\n   "\'strict\'", meaning that encoding errors raise "UnicodeError".\n   Other possible values are "\'ignore\'", "\'replace\'" and any other\n   name registered via "codecs.register_error()", see section *Codec\n   Base Classes*.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for other error handling schemes\n   added.\n\n   Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string.  Default encoding is the\n   current default string encoding.  *errors* may be given to set a\n   different error handling scheme.  The default for *errors* is\n   "\'strict\'", meaning that encoding errors raise a "UnicodeError".\n   Other 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   New in version 2.0.\n\n   Changed in version 2.3: Support for "\'xmlcharrefreplace\'" and\n   "\'backslashreplace\'" and other error handling schemes added.\n\n   Changed in version 2.7: 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 suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\n   Changed in version 2.5: Accept tuples as *suffix*.\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.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\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\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\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\n   This method of string formatting is the new standard in Python 3,\n   and should be preferred to the "%" formatting described in *String\n   Formatting Operations* in new code.\n\n   New in version 2.6.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  The separator between elements is the\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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\n   New in version 2.5.\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* is\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\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\n   New in version 2.5.\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 splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\n   New in version 2.4.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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 or "-1", then there is\n   no limit 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* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   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   For example, "\' 1  2   3  \'.split()" returns "[\'1\', \'2\', \'3\']", and\n   "\'  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. This method uses the *universal newlines* approach to\n   splitting lines. Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   For example, "\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()" returns "[\'ab\n   c\', \'\', \'de fg\', \'kl\']", while the same call with\n   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']".\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\n   Changed in version 2.5: Accept tuples as *prefix*.\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 *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\n   Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n   Return a copy of the string where all characters occurring in the\n   optional argument *deletechars* are removed, and the remaining\n   characters have been mapped through the given translation table,\n   which must be a string of length 256.\n\n   You can use the "maketrans()" helper function in the "string"\n   module to create a translation table. For string objects, set the\n   *table* argument to "None" for translations that only delete\n   characters:\n\n   >>> \'read this short text\'.translate(None, \'aeiou\')\n   \'rd ths shrt txt\'\n\n   New in version 2.6: Support for a "None" *table* argument.\n\n   For Unicode objects, the "translate()" method does not accept the\n   optional *deletechars* argument.  Instead, it returns a copy of the\n   *s* where all characters have been mapped through the given\n   translation table which must be a mapping of Unicode ordinals to\n   Unicode ordinals, Unicode strings or "None". Unmapped characters\n   are left untouched. Characters mapped to "None" are deleted.  Note,\n   a more flexible approach is to create a custom character mapping\n   codec using the "codecs" module (see "encodings.cp1251" for an\n   example).\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   For 8-bit strings, this method is locale-dependent.\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 or equal to "len(s)".\n\n   New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n   Return "True" if there are only numeric characters in S, "False"\n   otherwise. Numeric characters include digit characters, and all\n   characters that have the Unicode numeric value property, e.g.\n   U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n   Return "True" if there are only decimal characters in S, "False"\n   otherwise. Decimal characters include digit characters, and all\n   characters that can be used to form decimal-radix numbers, e.g.\n   U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the "%"\noperator (modulo).  This is also known as the string *formatting* or\n*interpolation* operator.  Given "format % values" (where *format* is\na string or Unicode object), "%" conversion specifications in *format*\nare replaced with zero or more elements of *values*.  The effect is\nsimilar to the using "sprintf()" in the C language.  If *format* is a\nUnicode object, or if any of the objects being converted using the\n"%s" conversion are Unicode objects, the result will also be a Unicode\nobject.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [5]  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\n   of 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\'" conversion  |\n|           | 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 ignored as\nit is not necessary for Python -- so e.g. "%ld" is identical 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()").    | (6)     |\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 "%r" conversion was added in Python 2.0.\n\n   The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a "unicode" string, the\n   resulting string will also be "unicode".\n\n   The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, "%s" conversions do not\nassume that "\'\\0\'" is the end of the string.\n\nChanged in version 2.7: "%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 "string"\nand "re".\n\n\nXRange Type\n===========\n\nThe "xrange" type is an immutable sequence which is commonly used for\nlooping.  The advantage of the "xrange" type is that an "xrange"\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\nXRange objects have very little behavior: they only support indexing,\niteration, and the "len()" function.\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\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)] = [x]" | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(x)"                  | same as "s[len(s):len(s)] = x"   | (3)                   |\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    | (4)                   |\n|                                | "s[k] == x" and "i <= k < j"     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | same as "s[i:i] = [x]"           | (5)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | same as "x = s[i]; del s[i];     | (6)                   |\n|                                | return x"                        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | same as "del s[s.index(x)]"      | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (7)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.sort([cmp[, key[,           | sort the items of *s* in place   | (7)(8)(9)(10)         |\n| reverse]]])"                   |                                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is  replacing.\n\n2. The C implementation of Python has historically accepted\n   multiple parameters and implicitly joined them into a tuple; this\n   no longer works in Python 2.0.  Use of this misfeature has been\n   deprecated since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises "ValueError" when *x* is not found in *s*. When a\n   negative index is passed as the second or third parameter to the\n   "index()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, "index()" didn\'t have arguments\n   for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n   "insert()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, all negative indices were\n   truncated to zero.\n\n6. The "pop()" method\'s optional argument *i* defaults to "-1", so\n   that by default the last item is removed and returned.\n\n7. The "sort()" and "reverse()" methods modify the list in place\n   for economy of space when sorting or reversing a large list.  To\n   remind you that they operate by side effect, they don\'t return the\n   sorted or reversed list.\n\n8. The "sort()" method takes optional arguments for controlling the\n   comparisons.\n\n   *cmp* specifies a custom comparison function of two arguments (list\n   items) which should return a negative, zero or positive number\n   depending on whether the first argument is considered smaller than,\n   equal to, or larger than the second argument: "cmp=lambda x,y:\n   cmp(x.lower(), y.lower())".  The default value is "None".\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".\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   In general, the *key* and *reverse* conversion processes are much\n   faster than specifying an equivalent *cmp* function.  This is\n   because *cmp* is called multiple times for each list element while\n   *key* and *reverse* touch each element only once.  Use\n   "functools.cmp_to_key()" to convert an old-style *cmp* function to\n   a *key* function.\n\n   Changed in version 2.3: Support for "None" as an equivalent to\n   omitting *cmp* was added.\n\n   Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the "sort()" method is guaranteed to\n   be stable.  A sort is stable if it guarantees not to change the\n   relative order of elements that compare equal --- this is helpful\n   for sorting in multiple passes (for example, sort by department,\n   then by salary grade).\n\n10. **CPython implementation detail:** While a list is being\n    sorted, the effect of attempting to mutate, or even inspect, the\n    list is undefined.  The C implementation of Python 2.3 and newer\n    makes the list appear empty for the duration, and raises\n    "ValueError" if it can detect that the list has been mutated\n    during a sort.\n',
+ 'typesseq': u'\nSequence Types --- "str", "unicode", "list", "tuple", "bytearray", "buffer", "xrange"\n*************************************************************************************\n\nThere are seven sequence types: strings, Unicode strings, lists,\ntuples, bytearrays, buffers, and xrange objects.\n\nFor other containers see the built in "dict" and "set" classes, and\nthe "collections" module.\n\nString literals are written in single or double quotes: "\'xyzzy\'",\n""frobozz"".  See String literals for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding "\'u\'" character: "u\'abc\'", "u"def"". In addition to\nthe functionality described here, there are also string-specific\nmethods described in the String Methods section. Lists are constructed\nwith square brackets, separating items with commas: "[a, b, c]".\nTuples are constructed by the comma operator (not within square\nbrackets), with or without enclosing parentheses, but an empty tuple\nmust have the enclosing parentheses, such as "a, b, c" or "()".  A\nsingle item tuple must have a trailing comma, such as "(d,)".\n\nBytearray objects are created with the built-in function\n"bytearray()".\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function "buffer()".  They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n"xrange()" function.  They don\'t support slicing, concatenation or\nrepetition, and using "in", "not in", "min()" or "max()" on them is\ninefficient.\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 the\ncorresponding numeric operations. [3] Additional methods are provided\nfor Mutable Sequence Types.\n\nThis table lists the sequence operations sorted in ascending priority.\nIn the table, *s* and *t* are sequences of the same type; *n*, *i* and\n*j* are integers:\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(x)"       | index of the first occurrence of |            |\n|                    | *x* in *s*                       |            |\n+--------------------+----------------------------------+------------+\n| "s.count(x)"       | total number of occurrences of   |            |\n|                    | *x* 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 compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see Comparisons in the language reference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the "in" and "not\n   in" operations act like a substring test.  In Python versions\n   before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n   beyond, *x* may be a string of any length.\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\n   the 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 "None",\n   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* is\n   greater than or equal to *j*, the slice is 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", "i+2*k",\n   "i+3*k" and so on, stopping when *j* is reached (but never\n   including *j*).  If *i* or *j* is greater than "len(s)", use\n   "len(s)".  If *i* or *j* are omitted or "None", they become "end"\n   values (which end depends on the sign of *k*).  Note, *k* cannot be\n   zero. If *k* is "None", it is treated like "1".\n\n6. **CPython implementation detail:** If *s* and *t* are both\n   strings, some Python implementations such as CPython can usually\n   perform an in-place optimization for assignments of the form "s = s\n   + t" or "s += t".  When applicable, this optimization makes\n   quadratic run-time much less likely.  This optimization is both\n   version and implementation dependent.  For performance sensitive\n   code, it is preferable to use the "str.join()" method which assures\n   consistent linear concatenation performance across versions and\n   implementations.\n\n   Changed in version 2.4: Formerly, string concatenation never\n   occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.  Some of them are also available on\n"bytearray" objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange section. To output formatted strings use\ntemplate strings or the "%" operator described in the String\nFormatting Operations section. Also, see the "re" module for string\nfunctions based 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\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.4: Support for the *fillchar* argument.\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.decode([encoding[, errors]])\n\n   Decodes the string using the codec registered for *encoding*.\n   *encoding* defaults to the default string encoding.  *errors* may\n   be given to set a different error handling scheme.  The default is\n   "\'strict\'", meaning that encoding errors raise "UnicodeError".\n   Other possible values are "\'ignore\'", "\'replace\'" and any other\n   name registered via "codecs.register_error()", see section Codec\n   Base Classes.\n\n   New in version 2.2.\n\n   Changed in version 2.3: Support for other error handling schemes\n   added.\n\n   Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n   Return an encoded version of the string.  Default encoding is the\n   current default string encoding.  *errors* may be given to set a\n   different error handling scheme.  The default for *errors* is\n   "\'strict\'", meaning that encoding errors raise a "UnicodeError".\n   Other 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   New in version 2.0.\n\n   Changed in version 2.3: Support for "\'xmlcharrefreplace\'" and\n   "\'backslashreplace\'" and other error handling schemes added.\n\n   Changed in version 2.7: 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 suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\n   Changed in version 2.5: Accept tuples as *suffix*.\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.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\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\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\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\n   This method of string formatting is the new standard in Python 3,\n   and should be preferred to the "%" formatting described in String\n   Formatting Operations in new code.\n\n   New in version 2.6.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\n   For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  The separator between elements is the\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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\n   New in version 2.5.\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* is\n   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 or\n   equal to "len(s)".\n\n   Changed in version 2.4: Support for the *fillchar* argument.\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\n   New in version 2.5.\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 splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\n   New in version 2.4.\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\n   Changed in version 2.2.2: Support for the *chars* argument.\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 or "-1", then there is\n   no limit 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* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   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   For example, "\' 1  2   3  \'.split()" returns "[\'1\', \'2\', \'3\']", and\n   "\'  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. This method uses the *universal newlines* approach to\n   splitting lines. Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   For example, "\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()" returns "[\'ab\n   c\', \'\', \'de fg\', \'kl\']", while the same call with\n   "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']".\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\n   Changed in version 2.5: Accept tuples as *prefix*.\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 *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\n   Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\n   For 8-bit strings, this method is locale-dependent.\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\n   For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n   Return a copy of the string where all characters occurring in the\n   optional argument *deletechars* are removed, and the remaining\n   characters have been mapped through the given translation table,\n   which must be a string of length 256.\n\n   You can use the "maketrans()" helper function in the "string"\n   module to create a translation table. For string objects, set the\n   *table* argument to "None" for translations that only delete\n   characters:\n\n   >>> \'read this short text\'.translate(None, \'aeiou\')\n   \'rd ths shrt txt\'\n\n   New in version 2.6: Support for a "None" *table* argument.\n\n   For Unicode objects, the "translate()" method does not accept the\n   optional *deletechars* argument.  Instead, it returns a copy of the\n   *s* where all characters have been mapped through the given\n   translation table which must be a mapping of Unicode ordinals to\n   Unicode ordinals, Unicode strings or "None". Unmapped characters\n   are left untouched. Characters mapped to "None" are deleted.  Note,\n   a more flexible approach is to create a custom character mapping\n   codec using the "codecs" module (see "encodings.cp1251" for an\n   example).\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   For 8-bit strings, this method is locale-dependent.\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 or equal to "len(s)".\n\n   New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n   Return "True" if there are only numeric characters in S, "False"\n   otherwise. Numeric characters include digit characters, and all\n   characters that have the Unicode numeric value property, e.g.\n   U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n   Return "True" if there are only decimal characters in S, "False"\n   otherwise. Decimal characters include digit characters, and all\n   characters that can be used to form decimal-radix numbers, e.g.\n   U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the "%"\noperator (modulo).  This is also known as the string *formatting* or\n*interpolation* operator.  Given "format % values" (where *format* is\na string or Unicode object), "%" conversion specifications in *format*\nare replaced with zero or more elements of *values*.  The effect is\nsimilar to the using "sprintf()" in the C language.  If *format* is a\nUnicode object, or if any of the objects being converted using the\n"%s" conversion are Unicode objects, the result will also be a Unicode\nobject.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [5]  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\n   of 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\'" conversion  |\n|           | 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 ignored as\nit is not necessary for Python -- so e.g. "%ld" is identical 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()").    | (6)     |\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 "%r" conversion was added in Python 2.0.\n\n   The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a "unicode" string, the\n   resulting string will also be "unicode".\n\n   The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, "%s" conversions do not\nassume that "\'\\0\'" is the end of the string.\n\nChanged in version 2.7: "%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 "string"\nand "re".\n\n\nXRange Type\n===========\n\nThe "xrange" type is an immutable sequence which is commonly used for\nlooping.  The advantage of the "xrange" type is that an "xrange"\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\nXRange objects have very little behavior: they only support indexing,\niteration, and the "len()" function.\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\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)] = [x]" | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(x)"                  | same as "s[len(s):len(s)] = x"   | (3)                   |\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    | (4)                   |\n|                                | "s[k] == x" and "i <= k < j"     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | same as "s[i:i] = [x]"           | (5)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | same as "x = s[i]; del s[i];     | (6)                   |\n|                                | return x"                        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | same as "del s[s.index(x)]"      | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (7)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.sort([cmp[, key[,           | sort the items of *s* in place   | (7)(8)(9)(10)         |\n| reverse]]])"                   |                                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is  replacing.\n\n2. The C implementation of Python has historically accepted\n   multiple parameters and implicitly joined them into a tuple; this\n   no longer works in Python 2.0.  Use of this misfeature has been\n   deprecated since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises "ValueError" when *x* is not found in *s*. When a\n   negative index is passed as the second or third parameter to the\n   "index()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, "index()" didn\'t have arguments\n   for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n   "insert()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, all negative indices were\n   truncated to zero.\n\n6. The "pop()" method\'s optional argument *i* defaults to "-1", so\n   that by default the last item is removed and returned.\n\n7. The "sort()" and "reverse()" methods modify the list in place\n   for economy of space when sorting or reversing a large list.  To\n   remind you that they operate by side effect, they don\'t return the\n   sorted or reversed list.\n\n8. The "sort()" method takes optional arguments for controlling the\n   comparisons.\n\n   *cmp* specifies a custom comparison function of two arguments (list\n   items) which should return a negative, zero or positive number\n   depending on whether the first argument is considered smaller than,\n   equal to, or larger than the second argument: "cmp=lambda x,y:\n   cmp(x.lower(), y.lower())".  The default value is "None".\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".\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   In general, the *key* and *reverse* conversion processes are much\n   faster than specifying an equivalent *cmp* function.  This is\n   because *cmp* is called multiple times for each list element while\n   *key* and *reverse* touch each element only once.  Use\n   "functools.cmp_to_key()" to convert an old-style *cmp* function to\n   a *key* function.\n\n   Changed in version 2.3: Support for "None" as an equivalent to\n   omitting *cmp* was added.\n\n   Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the "sort()" method is guaranteed to\n   be stable.  A sort is stable if it guarantees not to change the\n   relative order of elements that compare equal --- this is helpful\n   for sorting in multiple passes (for example, sort by department,\n   then by salary grade).\n\n10. **CPython implementation detail:** While a list is being\n    sorted, the effect of attempting to mutate, or even inspect, the\n    list is undefined.  The C implementation of Python 2.3 and newer\n    makes the list appear empty for the duration, and raises\n    "ValueError" if it can detect that the list has been mutated\n    during a sort.\n',
  'typesseq-mutable': u'\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\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)] = [x]" | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(x)"                  | same as "s[len(s):len(s)] = x"   | (3)                   |\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    | (4)                   |\n|                                | "s[k] == x" and "i <= k < j"     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | same as "s[i:i] = [x]"           | (5)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | same as "x = s[i]; del s[i];     | (6)                   |\n|                                | return x"                        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | same as "del s[s.index(x)]"      | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (7)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.sort([cmp[, key[,           | sort the items of *s* in place   | (7)(8)(9)(10)         |\n| reverse]]])"                   |                                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is  replacing.\n\n2. The C implementation of Python has historically accepted\n   multiple parameters and implicitly joined them into a tuple; this\n   no longer works in Python 2.0.  Use of this misfeature has been\n   deprecated since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises "ValueError" when *x* is not found in *s*. When a\n   negative index is passed as the second or third parameter to the\n   "index()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, "index()" didn\'t have arguments\n   for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n   "insert()" method, the list length is added, as for slice indices.\n   If it is still negative, it is truncated to zero, as for slice\n   indices.\n\n   Changed in version 2.3: Previously, all negative indices were\n   truncated to zero.\n\n6. The "pop()" method\'s optional argument *i* defaults to "-1", so\n   that by default the last item is removed and returned.\n\n7. The "sort()" and "reverse()" methods modify the list in place\n   for economy of space when sorting or reversing a large list.  To\n   remind you that they operate by side effect, they don\'t return the\n   sorted or reversed list.\n\n8. The "sort()" method takes optional arguments for controlling the\n   comparisons.\n\n   *cmp* specifies a custom comparison function of two arguments (list\n   items) which should return a negative, zero or positive number\n   depending on whether the first argument is considered smaller than,\n   equal to, or larger than the second argument: "cmp=lambda x,y:\n   cmp(x.lower(), y.lower())".  The default value is "None".\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".\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   In general, the *key* and *reverse* conversion processes are much\n   faster than specifying an equivalent *cmp* function.  This is\n   because *cmp* is called multiple times for each list element while\n   *key* and *reverse* touch each element only once.  Use\n   "functools.cmp_to_key()" to convert an old-style *cmp* function to\n   a *key* function.\n\n   Changed in version 2.3: Support for "None" as an equivalent to\n   omitting *cmp* was added.\n\n   Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the "sort()" method is guaranteed to\n   be stable.  A sort is stable if it guarantees not to change the\n   relative order of elements that compare equal --- this is helpful\n   for sorting in multiple passes (for example, sort by department,\n   then by salary grade).\n\n10. **CPython implementation detail:** While a list is being\n    sorted, the effect of attempting to mutate, or even inspect, the\n    list is undefined.  The C implementation of Python 2.3 and newer\n    makes the list appear empty for the duration, and raises\n    "ValueError" if it can detect that the list has been mutated\n    during a sort.\n',
  'unary': u'\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\nplain or long integer argument.  The bitwise inversion of "x" is\ndefined as "-(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': u'\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 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" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n',
- 'with': u'\nThe "with" statement\n********************\n\nNew in version 2.5.\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n     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, three\n   "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 reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   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\nNote: In Python 2.5, the "with" statement is only allowed when the\n  "with_statement" feature has been enabled.  It is always enabled in\n  Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n',
- 'yield': u'\nThe "yield" statement\n*********************\n\n   yield_stmt ::= yield_expression\n\nThe "yield" statement is only used when defining a generator function,\nand is only used in the body of the generator function. Using a\n"yield" statement in a function definition is sufficient to cause that\ndefinition to create a generator function instead of a normal\nfunction.\n\nWhen a generator function is called, it returns an iterator known as a\ngenerator iterator, or more commonly, a generator.  The body of the\ngenerator function is executed by calling the generator\'s "next()"\nmethod repeatedly until it raises an exception.\n\nWhen a "yield" statement is executed, the state of the generator is\nfrozen and the value of "expression_list" is returned to "next()"\'s\ncaller.  By "frozen" we mean that all local state is retained,\nincluding the current bindings of local variables, the instruction\npointer, and the internal evaluation stack: enough information is\nsaved so that the next time "next()" is invoked, the function can\nproceed exactly as if the "yield" statement were just another external\ncall.\n\nAs of Python version 2.5, the "yield" statement is now allowed in the\n"try" clause of a "try" ...  "finally" construct.  If the generator is\nnot resumed before it is finalized (by reaching a zero reference count\nor by being garbage collected), the generator-iterator\'s "close()"\nmethod will be called, allowing any pending "finally" clauses to\nexecute.\n\nFor full details of "yield" semantics, refer to the *Yield\nexpressions* section.\n\nNote: In Python 2.2, the "yield" statement was only allowed when the\n  "generators" feature has been enabled.  This "__future__" import\n  statement was used to enable the feature:\n\n     from __future__ import generators\n\nSee also: **PEP 0255** - Simple Generators\n\n     The proposal for adding generators and the "yield" statement to\n     Python.\n\n  **PEP 0342** - Coroutines via Enhanced Generators\n     The proposal that, among other generator enhancements, proposed\n     allowing "yield" to appear inside a "try" ... "finally" block.\n'}
+ 'with': u'\nThe "with" statement\n********************\n\nNew in version 2.5.\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n     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, three\n   "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 reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   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\nNote: In Python 2.5, the "with" statement is only allowed when the\n  "with_statement" feature has been enabled.  It is always enabled in\n  Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also: **PEP 0343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n',
+ 'yield': u'\nThe "yield" statement\n*********************\n\n   yield_stmt ::= yield_expression\n\nThe "yield" statement is only used when defining a generator function,\nand is only used in the body of the generator function. Using a\n"yield" statement in a function definition is sufficient to cause that\ndefinition to create a generator function instead of a normal\nfunction.\n\nWhen a generator function is called, it returns an iterator known as a\ngenerator iterator, or more commonly, a generator.  The body of the\ngenerator function is executed by calling the generator\'s "next()"\nmethod repeatedly until it raises an exception.\n\nWhen a "yield" statement is executed, the state of the generator is\nfrozen and the value of "expression_list" is returned to "next()"\'s\ncaller.  By "frozen" we mean that all local state is retained,\nincluding the current bindings of local variables, the instruction\npointer, and the internal evaluation stack: enough information is\nsaved so that the next time "next()" is invoked, the function can\nproceed exactly as if the "yield" statement were just another external\ncall.\n\nAs of Python version 2.5, the "yield" statement is now allowed in the\n"try" clause of a "try" ...  "finally" construct.  If the generator is\nnot resumed before it is finalized (by reaching a zero reference count\nor by being garbage collected), the generator-iterator\'s "close()"\nmethod will be called, allowing any pending "finally" clauses to\nexecute.\n\nFor full details of "yield" semantics, refer to the Yield expressions\nsection.\n\nNote: In Python 2.2, the "yield" statement was only allowed when the\n  "generators" feature has been enabled.  This "__future__" import\n  statement was used to enable the feature:\n\n     from __future__ import generators\n\nSee also: **PEP 0255** - Simple Generators\n\n     The proposal for adding generators and the "yield" statement to\n     Python.\n\n  **PEP 0342** - Coroutines via Enhanced Generators\n     The proposal that, among other generator enhancements, proposed\n     allowing "yield" to appear inside a "try" ... "finally" block.\n'}
index b65d8da..c1d0865 100644 (file)
@@ -179,6 +179,11 @@ class Message:
                 lst.append(line)
                 self.dict[headerseen] = line[len(headerseen)+1:].strip()
                 continue
+            elif headerseen is not None:
+                # An empty header name. These aren't allowed in HTTP, but it's
+                # probably a benign mistake. Don't add the header, just keep
+                # going.
+                continue
             else:
                 # It's not a header line; throw it back and stop here.
                 if not self.dict:
@@ -202,7 +207,7 @@ class Message:
         data in RFC 2822-like formats with special header formats.
         """
         i = line.find(':')
-        if i > 0:
+        if i > -1:
             return line[:i].lower()
         return None
 
index c8cba85..4f1e49d 100644 (file)
@@ -140,17 +140,21 @@ class Shelf(UserDict.DictMixin):
             pass
 
     def close(self):
-        self.sync()
-        try:
-            self.dict.close()
-        except AttributeError:
-            pass
-        # Catch errors that may happen when close is called from __del__
-        # because CPython is in interpreter shutdown.
+        if self.dict is None:
+            return
         try:
-            self.dict = _ClosedDict()
-        except (NameError, TypeError):
-            self.dict = None
+            self.sync()
+            try:
+                self.dict.close()
+            except AttributeError:
+                pass
+        finally:
+            # Catch errors that may happen when close is called from __del__
+            # because CPython is in interpreter shutdown.
+            try:
+                self.dict = _ClosedDict()
+            except:
+                self.dict = None
 
     def __del__(self):
         if not hasattr(self, 'writeback'):
index e12f791..e78a575 100644 (file)
@@ -362,7 +362,7 @@ def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
     archive_name = base_name + '.tar' + compress_ext.get(compress, '')
     archive_dir = os.path.dirname(archive_name)
 
-    if not os.path.exists(archive_dir):
+    if archive_dir and not os.path.exists(archive_dir):
         if logger is not None:
             logger.info("creating %s", archive_dir)
         if not dry_run:
@@ -426,7 +426,7 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
     zip_filename = base_name + ".zip"
     archive_dir = os.path.dirname(base_name)
 
-    if not os.path.exists(archive_dir):
+    if archive_dir and not os.path.exists(archive_dir):
         if logger is not None:
             logger.info("creating %s", archive_dir)
         if not dry_run:
index d2e18f1..4a09f3c 100644 (file)
@@ -436,7 +436,7 @@ def setcopyright():
     for supporting Python development.  See www.python.org for more information.""")
     here = os.path.dirname(os.__file__)
     __builtin__.license = _Printer(
-        "license", "See http://www.python.org/psf/license/",
+        "license", "See https://www.python.org/psf/license/",
         ["LICENSE.txt", "LICENSE"],
         [os.path.join(here, os.pardir), here, os.curdir])
 
index d1c2806..8388b98 100755 (executable)
@@ -750,12 +750,16 @@ class SMTP:
 
     def close(self):
         """Close the connection to the SMTP server."""
-        if self.file:
-            self.file.close()
-        self.file = None
-        if self.sock:
-            self.sock.close()
-        self.sock = None
+        try:
+            file = self.file
+            self.file = None
+            if file:
+                file.close()
+        finally:
+            sock = self.sock
+            self.sock = None
+            if sock:
+                sock.close()
 
 
     def quit(self):
index aac04f6..614af29 100644 (file)
@@ -67,7 +67,6 @@ else:
     from _ssl import SSLError as sslerror
     from _ssl import \
          RAND_add, \
-         RAND_egd, \
          RAND_status, \
          SSL_ERROR_ZERO_RETURN, \
          SSL_ERROR_WANT_READ, \
@@ -78,6 +77,11 @@ else:
          SSL_ERROR_WANT_CONNECT, \
          SSL_ERROR_EOF, \
          SSL_ERROR_INVALID_ERROR_CODE
+    try:
+        from _ssl import RAND_egd
+    except ImportError:
+        # LibreSSL does not provide RAND_egd
+        pass
 
 import os, sys, warnings
 
index b85ce88..c29cc16 100644 (file)
@@ -69,6 +69,8 @@ class Pattern:
         self.open = []
         self.groups = 1
         self.groupdict = {}
+        self.lookbehind = 0
+
     def opengroup(self, name=None):
         gid = self.groups
         self.groups = gid + 1
@@ -299,6 +301,11 @@ def _escape(source, escape, state):
             if group < state.groups:
                 if not state.checkgroup(group):
                     raise error, "cannot refer to open group"
+                if state.lookbehind:
+                    import warnings
+                    warnings.warn('group references in lookbehind '
+                                  'assertions are not supported',
+                                  RuntimeWarning)
                 return GROUPREF, group
             raise ValueError
         if len(escape) == 2:
@@ -578,6 +585,11 @@ def _parse(source, state):
                         if gid is None:
                             msg = "unknown group name: {0!r}".format(name)
                             raise error(msg)
+                        if state.lookbehind:
+                            import warnings
+                            warnings.warn('group references in lookbehind '
+                                          'assertions are not supported',
+                                          RuntimeWarning)
                         subpatternappend((GROUPREF, gid))
                         continue
                     else:
@@ -606,7 +618,10 @@ def _parse(source, state):
                             raise error, "syntax error"
                         dir = -1 # lookbehind
                         char = sourceget()
+                        state.lookbehind += 1
                     p = _parse_sub(source, state)
+                    if dir < 0:
+                        state.lookbehind -= 1
                     if not sourcematch(")"):
                         raise error, "unbalanced parenthesis"
                     if char == "=":
@@ -637,6 +652,11 @@ def _parse(source, state):
                             condgroup = int(condname)
                         except ValueError:
                             raise error, "bad character in group name"
+                    if state.lookbehind:
+                        import warnings
+                        warnings.warn('group references in lookbehind '
+                                      'assertions are not supported',
+                                      RuntimeWarning)
                 else:
                     # flags
                     if not source.next in FLAGS:
index 0f82227..5df6ed3 100644 (file)
@@ -103,10 +103,13 @@ from _ssl import (
     SSLSyscallError, SSLEOFError,
     )
 from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
-from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
-    VERIFY_X509_STRICT)
 from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
-from _ssl import RAND_status, RAND_egd, RAND_add
+from _ssl import RAND_status, RAND_add
+try:
+    from _ssl import RAND_egd
+except ImportError:
+    # LibreSSL does not provide RAND_egd
+    pass
 
 def _import_symbols(prefix):
     for n in dir(_ssl):
@@ -117,8 +120,9 @@ _import_symbols('OP_')
 _import_symbols('ALERT_DESCRIPTION_')
 _import_symbols('SSL_ERROR_')
 _import_symbols('PROTOCOL_')
+_import_symbols('VERIFY_')
 
-from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
+from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
 
 from _ssl import _OPENSSL_API_VERSION
 
@@ -152,14 +156,12 @@ else:
 #   * Prefer any AES-GCM over any AES-CBC for better performance and security
 #   * Then Use HIGH cipher suites as a fallback
 #   * Then Use 3DES as fallback which is secure but slow
-#   * Finally use RC4 as a fallback which is problematic but needed for
-#     compatibility some times.
 #   * Disable NULL authentication, NULL encryption, and MD5 MACs for security
 #     reasons
 _DEFAULT_CIPHERS = (
     'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
-    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
-    'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
+    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
+    '!eNULL:!MD5'
 )
 
 # Restricted and more secure ciphers for the server side
@@ -360,6 +362,17 @@ class SSLContext(_SSLContext):
 
         self._set_npn_protocols(protos)
 
+    def set_alpn_protocols(self, alpn_protocols):
+        protos = bytearray()
+        for protocol in alpn_protocols:
+            b = protocol.encode('ascii')
+            if len(b) == 0 or len(b) > 255:
+                raise SSLError('ALPN protocols must be 1 to 255 in length')
+            protos.append(len(b))
+            protos.extend(b)
+
+        self._set_alpn_protocols(protos)
+
     def _load_windows_store_certs(self, storename, purpose):
         certs = bytearray()
         for cert, encoding, trust in enum_certificates(storename):
@@ -642,6 +655,13 @@ class SSLSocket(socket):
         else:
             return self._sslobj.selected_npn_protocol()
 
+    def selected_alpn_protocol(self):
+        self._checkClosed()
+        if not self._sslobj or not _ssl.HAS_ALPN:
+            return None
+        else:
+            return self._sslobj.selected_alpn_protocol()
+
     def cipher(self):
         self._checkClosed()
         if not self._sslobj:
index d762e04..23608b4 100644 (file)
@@ -145,7 +145,11 @@ class Template:
         raise ValueError('Invalid placeholder in string: line %d, col %d' %
                          (lineno, colno))
 
-    def substitute(self, *args, **kws):
+    def substitute(*args, **kws):
+        if not args:
+            raise TypeError("descriptor 'substitute' of 'Template' object "
+                            "needs an argument")
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed
         if len(args) > 1:
             raise TypeError('Too many positional arguments')
         if not args:
@@ -171,7 +175,11 @@ class Template:
                              self.pattern)
         return self.pattern.sub(convert, self.template)
 
-    def safe_substitute(self, *args, **kws):
+    def safe_substitute(*args, **kws):
+        if not args:
+            raise TypeError("descriptor 'safe_substitute' of 'Template' object "
+                            "needs an argument")
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed
         if len(args) > 1:
             raise TypeError('Too many positional arguments')
         if not args:
@@ -535,7 +543,19 @@ except ImportError:
 # The field name parser is implemented in str._formatter_field_name_split
 
 class Formatter(object):
-    def format(self, format_string, *args, **kwargs):
+    def format(*args, **kwargs):
+        if not args:
+            raise TypeError("descriptor 'format' of 'Formatter' object "
+                            "needs an argument")
+        self, args = args[0], args[1:]  # allow the "self" keyword be passed
+        try:
+            format_string, args = args[0], args[1:] # allow the "format_string" keyword be passed
+        except IndexError:
+            if 'format_string' in kwargs:
+                format_string = kwargs.pop('format_string')
+            else:
+                raise TypeError("format() missing 1 required positional "
+                                "argument: 'format_string'")
         return self.vformat(format_string, args, kwargs)
 
     def vformat(self, format_string, args, kwargs):
index b0d1292..082f361 100644 (file)
@@ -41,6 +41,7 @@ __credits__ = "Gustavo Niemeyer, Niels Gust
 #---------
 # Imports
 #---------
+from __builtin__ import open as bltn_open
 import sys
 import os
 import shutil
@@ -491,26 +492,26 @@ class _Stream:
         if self.closed:
             return
 
-        if self.mode == "w" and self.comptype != "tar":
-            self.buf += self.cmp.flush()
-
-        if self.mode == "w" and self.buf:
-            self.fileobj.write(self.buf)
-            self.buf = ""
-            if self.comptype == "gz":
-                # The native zlib crc is an unsigned 32-bit integer, but
-                # the Python wrapper implicitly casts that to a signed C
-                # long.  So, on a 32-bit box self.crc may "look negative",
-                # while the same crc on a 64-bit box may "look positive".
-                # To avoid irksome warnings from the `struct` module, force
-                # it to look positive on all boxes.
-                self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL))
-                self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL))
-
-        if not self._extfileobj:
-            self.fileobj.close()
-
         self.closed = True
+        try:
+            if self.mode == "w" and self.comptype != "tar":
+                self.buf += self.cmp.flush()
+
+            if self.mode == "w" and self.buf:
+                self.fileobj.write(self.buf)
+                self.buf = ""
+                if self.comptype == "gz":
+                    # The native zlib crc is an unsigned 32-bit integer, but
+                    # the Python wrapper implicitly casts that to a signed C
+                    # long.  So, on a 32-bit box self.crc may "look negative",
+                    # while the same crc on a 64-bit box may "look positive".
+                    # To avoid irksome warnings from the `struct` module, force
+                    # it to look positive on all boxes.
+                    self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL))
+                    self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL))
+        finally:
+            if not self._extfileobj:
+                self.fileobj.close()
 
     def _init_read_gz(self):
         """Initialize for reading a gzip compressed fileobj.
@@ -1795,18 +1796,19 @@ class TarFile(object):
         if self.closed:
             return
 
-        if self.mode in "aw":
-            self.fileobj.write(NUL * (BLOCKSIZE * 2))
-            self.offset += (BLOCKSIZE * 2)
-            # fill up the end with zero-blocks
-            # (like option -b20 for tar does)
-            blocks, remainder = divmod(self.offset, RECORDSIZE)
-            if remainder > 0:
-                self.fileobj.write(NUL * (RECORDSIZE - remainder))
-
-        if not self._extfileobj:
-            self.fileobj.close()
         self.closed = True
+        try:
+            if self.mode in "aw":
+                self.fileobj.write(NUL * (BLOCKSIZE * 2))
+                self.offset += (BLOCKSIZE * 2)
+                # fill up the end with zero-blocks
+                # (like option -b20 for tar does)
+                blocks, remainder = divmod(self.offset, RECORDSIZE)
+                if remainder > 0:
+                    self.fileobj.write(NUL * (RECORDSIZE - remainder))
+        finally:
+            if not self._extfileobj:
+                self.fileobj.close()
 
     def getmember(self, name):
         """Return a TarInfo object for member `name'. If `name' can not be
@@ -2611,5 +2613,4 @@ def is_tarfile(name):
     except TarError:
         return False
 
-bltn_open = open
 open = TarFile.open
index 88aa482..2eaa8e3 100644 (file)
@@ -254,12 +254,13 @@ class Telnet:
 
     def close(self):
         """Close the connection."""
-        if self.sock:
-            self.sock.close()
+        sock = self.sock
         self.sock = 0
         self.eof = 1
         self.iacseq = ''
         self.sb = 0
+        if sock:
+            sock.close()
 
     def get_socket(self):
         """Return the socket object used internally."""
index a4083f7..fbda8eb 100644 (file)
@@ -413,9 +413,11 @@ class _TemporaryFileWrapper:
         def close(self):
             if not self.close_called:
                 self.close_called = True
-                self.file.close()
-                if self.delete:
-                    self.unlink(self.name)
+                try:
+                    self.file.close()
+                finally:
+                    if self.delete:
+                        self.unlink(self.name)
 
         def __del__(self):
             self.close()
index d394831..f85becb 100644 (file)
@@ -24,6 +24,7 @@ __all__ = (
 __version__ = '1.0'
 
 
+import __builtin__
 import inspect
 import pprint
 import sys
@@ -32,7 +33,7 @@ from types import ModuleType
 from functools import wraps, partial
 
 
-_builtins = {name for name in __builtins__ if not name.startswith('_')}
+_builtins = {name for name in dir(__builtin__) if not name.startswith('_')}
 
 BaseExceptions = (BaseException,)
 if 'java' in sys.platform:
index f4abd2a..7ed0414 100644 (file)
@@ -61,8 +61,9 @@ class AudioTests:
         self.assertEqual(params,
                 (nchannels, sampwidth, framerate, nframes, comptype, compname))
 
-        dump = pickle.dumps(params)
-        self.assertEqual(pickle.loads(dump), params)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            dump = pickle.dumps(params, proto)
+            self.assertEqual(pickle.loads(dump), params)
 
 
 class AudioWriteTests(AudioTests):
diff --git a/Lib/test/dh1024.pem b/Lib/test/dh1024.pem
new file mode 100644 (file)
index 0000000..a391176
--- /dev/null
@@ -0,0 +1,7 @@
+-----BEGIN DH PARAMETERS-----
+MIGHAoGBAIbzw1s9CT8SV5yv6L7esdAdZYZjPi3qWFs61CYTFFQnf2s/d09NYaJt
+rrvJhIzWavqnue71qXCf83/J3nz3FEwUU/L0mGyheVbsSHiI64wUo3u50wK5Igo0
+RNs/LD0irs7m0icZ//hijafTU+JOBiuA8zMI+oZfU7BGuc9XrUprAgEC
+-----END DH PARAMETERS-----
+
+Generated with: openssl dhparam -out dh1024.pem  1024
diff --git a/Lib/test/dh512.pem b/Lib/test/dh512.pem
deleted file mode 100644 (file)
index 200d16c..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
------BEGIN DH PARAMETERS-----
-MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak
-XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC
------END DH PARAMETERS-----
-
-These are the 512 bit DH parameters from "Assigned Number for SKIP Protocols"
-(http://www.skip-vpn.org/spec/numbers.html).
-See there for how they were generated.
-Note that g is not a generator, but this is not a problem since p is a safe prime.
index 966f9bd..2ff75c4 100644 (file)
@@ -39,8 +39,12 @@ class Bunch(object):
                 self.finished.append(tid)
                 while not self._can_exit:
                     _wait()
-        for i in range(n):
-            start_new_thread(task, ())
+        try:
+            for i in range(n):
+                start_new_thread(task, ())
+        except:
+            self._can_exit = True
+            raise
 
     def wait_for_started(self):
         while len(self.started) < self.n:
index b48cba5..3a8ad91 100755 (executable)
@@ -773,7 +773,7 @@ class saved_test_environment:
 
     resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
                  'os.environ', 'sys.path', 'asyncore.socket_map',
-                 'test_support.TESTFN',
+                 'files',
                 )
 
     def get_sys_argv(self):
@@ -840,6 +840,17 @@ class saved_test_environment:
             elif os.path.isdir(test_support.TESTFN):
                 shutil.rmtree(test_support.TESTFN)
 
+    def get_files(self):
+        return sorted(fn + ('/' if os.path.isdir(fn) else '')
+                      for fn in os.listdir(os.curdir))
+    def restore_files(self, saved_value):
+        fn = test_support.TESTFN
+        if fn not in saved_value and (fn + '/') not in saved_value:
+            if os.path.isfile(fn):
+                test_support.unlink(fn)
+            elif os.path.isdir(fn):
+                test_support.rmtree(fn)
+
     def resource_info(self):
         for name in self.resources:
             method_suffix = name.replace('.', '_')
@@ -1191,6 +1202,7 @@ _expectations = {
         test_pwd
         test_resource
         test_signal
+        test_spwd
         test_threadsignals
         test_timing
         test_wait3
index afcb926..88f2c44 100644 (file)
@@ -22,7 +22,7 @@ candidate_locales = ['es_UY', 'fr_FR', 'fi_FI', 'es_CO', 'pt_PT', 'it_IT',
     'da_DK', 'nn_NO', 'cs_CZ', 'de_LU', 'es_BO', 'sq_AL', 'sk_SK', 'fr_CH',
     'de_DE', 'sr_YU', 'br_FR', 'nl_BE', 'sv_FI', 'pl_PL', 'fr_CA', 'fo_FO',
     'bs_BA', 'fr_LU', 'kl_GL', 'fa_IR', 'de_BE', 'sv_SE', 'it_CH', 'uk_UA',
-    'eu_ES', 'vi_VN', 'af_ZA', 'nb_NO', 'en_DK', 'tg_TJ', 'en_US',
+    'eu_ES', 'vi_VN', 'af_ZA', 'nb_NO', 'en_DK', 'tg_TJ', 'ps_AF.UTF-8', 'en_US',
     'es_ES.ISO8859-1', 'fr_FR.ISO8859-15', 'ru_RU.KOI8-R', 'ko_KR.eucKR']
 
 # Workaround for MSVC6(debug) crash bug
@@ -35,7 +35,12 @@ if "MSC v.1200" in sys.version:
 # List known locale values to test against when available.
 # Dict formatted as ``<locale> : (<decimal_point>, <thousands_sep>)``.  If a
 # value is not known, use '' .
-known_numerics = {'fr_FR' : (',', ''), 'en_US':('.', ',')}
+known_numerics = {
+    'en_US': ('.', ','),
+    'fr_FR' : (',', ' '),
+    'de_DE' : (',', '.'),
+    'ps_AF.UTF-8' : ('\xd9\xab', '\xd9\xac'),
+}
 
 class _LocaleTests(unittest.TestCase):
 
@@ -64,10 +69,12 @@ class _LocaleTests(unittest.TestCase):
                                     calc_value, known_value,
                                     calc_type, data_type, set_locale,
                                     used_locale))
+            return True
 
     @unittest.skipUnless(nl_langinfo, "nl_langinfo is not available")
     def test_lc_numeric_nl_langinfo(self):
         # Test nl_langinfo against known values
+        tested = False
         for loc in candidate_locales:
             try:
                 setlocale(LC_NUMERIC, loc)
@@ -75,21 +82,30 @@ class _LocaleTests(unittest.TestCase):
                 continue
             for li, lc in ((RADIXCHAR, "decimal_point"),
                             (THOUSEP, "thousands_sep")):
-                self.numeric_tester('nl_langinfo', nl_langinfo(li), lc, loc)
+                if self.numeric_tester('nl_langinfo', nl_langinfo(li), lc, loc):
+                    tested = True
+        if not tested:
+            self.skipTest('no suitable locales')
 
     def test_lc_numeric_localeconv(self):
         # Test localeconv against known values
+        tested = False
         for loc in candidate_locales:
             try:
                 setlocale(LC_NUMERIC, loc)
             except Error:
                 continue
+            formatting = localeconv()
             for lc in ("decimal_point", "thousands_sep"):
-                self.numeric_tester('localeconv', localeconv()[lc], lc, loc)
+                if self.numeric_tester('localeconv', formatting[lc], lc, loc):
+                    tested = True
+        if not tested:
+            self.skipTest('no suitable locales')
 
     @unittest.skipUnless(nl_langinfo, "nl_langinfo is not available")
     def test_lc_numeric_basic(self):
         # Test nl_langinfo against localeconv
+        tested = False
         for loc in candidate_locales:
             try:
                 setlocale(LC_NUMERIC, loc)
@@ -108,10 +124,14 @@ class _LocaleTests(unittest.TestCase):
                                 "(set to %s, using %s)" % (
                                                 nl_radixchar, li_radixchar,
                                                 loc, set_locale))
+                tested = True
+        if not tested:
+            self.skipTest('no suitable locales')
 
     def test_float_parsing(self):
         # Bug #1391872: Test whether float parsing is okay on European
         # locales.
+        tested = False
         for loc in candidate_locales:
             try:
                 setlocale(LC_NUMERIC, loc)
@@ -129,6 +149,10 @@ class _LocaleTests(unittest.TestCase):
             if localeconv()['decimal_point'] != '.':
                 self.assertRaises(ValueError, float,
                                   localeconv()['decimal_point'].join(['1', '23']))
+            tested = True
+        if not tested:
+            self.skipTest('no suitable locales')
+
 
 def test_main():
     run_unittest(_LocaleTests)
index cfc491d..d4e9de5 100644 (file)
@@ -322,12 +322,16 @@ class AIFCLowLevelTest(unittest.TestCase):
 
     def test_write_aiff_by_extension(self):
         sampwidth = 2
-        fout = self.fout = aifc.open(TESTFN + '.aiff', 'wb')
+        filename = TESTFN + '.aiff'
+        self.addCleanup(unlink, filename)
+
+        fout = self.fout = aifc.open(filename, 'wb')
         fout.setparams((1, sampwidth, 1, 1, 'ULAW', ''))
         frames = '\x00' * fout.getnchannels() * sampwidth
         fout.writeframes(frames)
         fout.close()
-        f = self.f = aifc.open(TESTFN + '.aiff', 'rb')
+
+        f = self.f = aifc.open(filename, 'rb')
         self.assertEqual(f.getcomptype(), 'NONE')
         f.close()
 
index b74b622..915e989 100644 (file)
@@ -646,7 +646,7 @@ class TestOptionalsChoices(ParserTestCase):
 
 
 class TestOptionalsRequired(ParserTestCase):
-    """Tests the an optional action that is required"""
+    """Tests an optional action that is required"""
 
     argument_signatures = [
         Sig('-x', type=int, required=True),
index c41c373..c81c1a1 100644 (file)
@@ -33,6 +33,11 @@ import sys
 #    memuse-per-size should remain sane (less than a few thousand); if your
 #    test uses more, adjust 'size' upward, instead.
 
+if test_support.have_unicode:
+    character_size = 4 if sys.maxunicode > 0xFFFF else 2
+else:
+    character_size = 1
+
 class StrTest(unittest.TestCase):
     @bigmemtest(minsize=_2G, memuse=2)
     def test_capitalize(self, size):
@@ -54,7 +59,8 @@ class StrTest(unittest.TestCase):
         self.assertEqual(s[lpadsize:-rpadsize], SUBSTR)
         self.assertEqual(s.strip(), SUBSTR.strip())
 
-    @precisionbigmemtest(size=_2G - 1, memuse=1)
+    @test_support.requires_unicode
+    @precisionbigmemtest(size=_2G - 1, memuse=character_size)
     def test_center_unicode(self, size):
         SUBSTR = u' abc def ghi'
         try:
@@ -81,7 +87,8 @@ class StrTest(unittest.TestCase):
         self.assertEqual(s.count('i'), 1)
         self.assertEqual(s.count('j'), 0)
 
-    @bigmemtest(minsize=_2G + 2, memuse=3)
+    @test_support.requires_unicode
+    @bigmemtest(minsize=_2G + 2, memuse=1 + character_size)
     def test_decode(self, size):
         s = '.' * size
         self.assertEqual(len(s.decode('utf-8')), size)
@@ -93,45 +100,30 @@ class StrTest(unittest.TestCase):
         s = c * size
         self.assertEqual(len(s.encode(enc)), expectedsize)
 
-    @bigmemtest(minsize=_2G + 2, memuse=3)
+    @test_support.requires_unicode
+    @bigmemtest(minsize=_2G + 2, memuse=character_size + 4)
     def test_encode(self, size):
-        return self.basic_encode_test(size, 'utf-8')
+        self.basic_encode_test(size, 'utf-8')
 
-    @precisionbigmemtest(size=_4G // 6 + 2, memuse=2)
+    @test_support.requires_unicode
+    @precisionbigmemtest(size=_4G // 6 + 2, memuse=character_size + 6)
     def test_encode_raw_unicode_escape(self, size):
-        try:
-            return self.basic_encode_test(size, 'raw_unicode_escape')
-        except MemoryError:
-            pass # acceptable on 32-bit
+        self.basic_encode_test(size, 'raw_unicode_escape')
 
-    @precisionbigmemtest(size=_4G // 5 + 70, memuse=3)
+    @test_support.requires_unicode
+    @precisionbigmemtest(size=_4G // 5 + 70, memuse=character_size + 8)
     def test_encode_utf7(self, size):
-        try:
-            return self.basic_encode_test(size, 'utf7')
-        except MemoryError:
-            pass # acceptable on 32-bit
+        self.basic_encode_test(size, 'utf7')
 
-    @precisionbigmemtest(size=_4G // 4 + 5, memuse=6)
+    @test_support.requires_unicode
+    @precisionbigmemtest(size=_4G // 4 + 5, memuse=character_size + 4)
     def test_encode_utf32(self, size):
-        try:
-            return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4)
-        except MemoryError:
-            pass # acceptable on 32-bit
+        self.basic_encode_test(size, 'utf32', expectedsize=4*size+4)
 
+    @test_support.requires_unicode
     @precisionbigmemtest(size=_2G-1, memuse=4)
     def test_decodeascii(self, size):
-        return self.basic_encode_test(size, 'ascii', c='A')
-
-    @precisionbigmemtest(size=_4G // 5, memuse=6+2)
-    def test_unicode_repr_oflw(self, size):
-        self.skipTest("test crashes - see issue #14904")
-        try:
-            s = u"\uAAAA"*size
-            r = repr(s)
-        except MemoryError:
-            pass # acceptable on 32-bit
-        else:
-            self.assertTrue(s == eval(r))
+        self.basic_encode_test(size, 'ascii', c='A')
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_endswith(self, size):
@@ -516,10 +508,27 @@ class StrTest(unittest.TestCase):
         self.assertEqual(s.count('\\'), size)
         self.assertEqual(s.count('0'), size * 2)
 
-    @bigmemtest(minsize=2**32 // 5, memuse=6+2)
+    @test_support.requires_unicode
+    @bigmemtest(minsize=2**32 // 6, memuse=character_size + 6)
     def test_unicode_repr(self, size):
-        s = u"\uAAAA" * size
-        self.assertTrue(len(repr(s)) > size)
+        s = unichr(0xABCD) * size
+        try:
+            r = repr(s)
+            self.assertEqual(len(r), 3 + 6 * size)
+            self.assertTrue(r.endswith(r"\uabcd'"), r[-10:])
+        finally:
+            s = r = None
+
+    @test_support.requires_unicode
+    @precisionbigmemtest(size=_4G // 6 + 1, memuse=character_size + 6)
+    def test_unicode_repr_oflw(self, size):
+        s = unichr(0xABCD) * size
+        try:
+            r = repr(s)
+            self.assertEqual(len(r), 3 + 6 * size)
+            self.assertTrue(r.endswith(r"\uabcd'"), r[-10:])
+        finally:
+            r = s = None
 
     # This test is meaningful even with size < 2G, as long as the
     # doubled string is > 2G (but it tests more if both are > 2G :)
index f825f1c..d40b672 100644 (file)
@@ -137,6 +137,14 @@ class BinASCIITest(unittest.TestCase):
         # Issue #7701 (crash on a pydebug build)
         self.assertEqual(binascii.b2a_uu('x'), '!>   \n')
 
+    def test_crc_hqx(self):
+        crc = binascii.crc_hqx(self.type2test(b"Test the CRC-32 of"), 0)
+        crc = binascii.crc_hqx(self.type2test(b" this string."), crc)
+        self.assertEqual(crc, 14290)
+
+        self.assertRaises(TypeError, binascii.crc_hqx)
+        self.assertRaises(TypeError, binascii.crc_hqx, self.type2test(b''))
+
     def test_crc32(self):
         crc = binascii.crc32(self.type2test("Test the CRC-32 of"))
         crc = binascii.crc32(self.type2test(" this string."), crc)
index 16cd1aa..e3b4775 100644 (file)
@@ -305,42 +305,40 @@ class BoolTest(unittest.TestCase):
 
     def test_pickle(self):
         import pickle
-        self.assertIs(pickle.loads(pickle.dumps(True)), True)
-        self.assertIs(pickle.loads(pickle.dumps(False)), False)
-        self.assertIs(pickle.loads(pickle.dumps(True, True)), True)
-        self.assertIs(pickle.loads(pickle.dumps(False, True)), False)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            self.assertIs(pickle.loads(pickle.dumps(True, proto)), True)
+            self.assertIs(pickle.loads(pickle.dumps(False, proto)), False)
 
     def test_cpickle(self):
         import cPickle
-        self.assertIs(cPickle.loads(cPickle.dumps(True)), True)
-        self.assertIs(cPickle.loads(cPickle.dumps(False)), False)
-        self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True)
-        self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False)
+        for proto in range(cPickle.HIGHEST_PROTOCOL + 1):
+            self.assertIs(cPickle.loads(cPickle.dumps(True, proto)), True)
+            self.assertIs(cPickle.loads(cPickle.dumps(False, proto)), False)
 
     def test_mixedpickle(self):
         import pickle, cPickle
-        self.assertIs(pickle.loads(cPickle.dumps(True)), True)
-        self.assertIs(pickle.loads(cPickle.dumps(False)), False)
-        self.assertIs(pickle.loads(cPickle.dumps(True, True)), True)
-        self.assertIs(pickle.loads(cPickle.dumps(False, True)), False)
-
-        self.assertIs(cPickle.loads(pickle.dumps(True)), True)
-        self.assertIs(cPickle.loads(pickle.dumps(False)), False)
-        self.assertIs(cPickle.loads(pickle.dumps(True, True)), True)
-        self.assertIs(cPickle.loads(pickle.dumps(False, True)), False)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            self.assertIs(pickle.loads(cPickle.dumps(True, proto)), True)
+            self.assertIs(pickle.loads(cPickle.dumps(False, proto)), False)
+            self.assertIs(cPickle.loads(pickle.dumps(True, proto)), True)
+            self.assertIs(cPickle.loads(pickle.dumps(False, proto)), False)
 
     def test_picklevalues(self):
         import pickle, cPickle
 
         # Test for specific backwards-compatible pickle values
-        self.assertEqual(pickle.dumps(True), "I01\n.")
-        self.assertEqual(pickle.dumps(False), "I00\n.")
-        self.assertEqual(cPickle.dumps(True), "I01\n.")
-        self.assertEqual(cPickle.dumps(False), "I00\n.")
-        self.assertEqual(pickle.dumps(True, True), "I01\n.")
-        self.assertEqual(pickle.dumps(False, True), "I00\n.")
-        self.assertEqual(cPickle.dumps(True, True), "I01\n.")
-        self.assertEqual(cPickle.dumps(False, True), "I00\n.")
+        self.assertEqual(pickle.dumps(True, protocol=0), "I01\n.")
+        self.assertEqual(pickle.dumps(False, protocol=0), "I00\n.")
+        self.assertEqual(cPickle.dumps(True, protocol=0), "I01\n.")
+        self.assertEqual(cPickle.dumps(False, protocol=0), "I00\n.")
+        self.assertEqual(pickle.dumps(True, protocol=1), "I01\n.")
+        self.assertEqual(pickle.dumps(False, protocol=1), "I00\n.")
+        self.assertEqual(cPickle.dumps(True, protocol=1), "I01\n.")
+        self.assertEqual(cPickle.dumps(False, protocol=1), "I00\n.")
+        self.assertEqual(pickle.dumps(True, protocol=2), b'\x80\x02\x88.')
+        self.assertEqual(pickle.dumps(False, protocol=2), b'\x80\x02\x89.')
+        self.assertEqual(cPickle.dumps(True, protocol=2), b'\x80\x02\x88.')
+        self.assertEqual(cPickle.dumps(False, protocol=2), b'\x80\x02\x89.')
 
     def test_convert_to_bool(self):
         # Verify that TypeError occurs when bad things are returned
index e2c222a..bf5eb20 100644 (file)
@@ -1,4 +1,4 @@
-from test import test_support
+from test import test_support as support
 from test.test_support import TESTFN, _4G, bigmemtest, import_module, findfile
 
 import unittest
@@ -306,10 +306,8 @@ class BZ2FileTest(BaseTest):
                 for i in range(5):
                     f.write(data)
             threads = [threading.Thread(target=comp) for i in range(nthreads)]
-            for t in threads:
-                t.start()
-            for t in threads:
-                t.join()
+            with support.start_threads(threads):
+                pass
 
     def testMixedIterationReads(self):
         # Issue #8397: mixed iteration and reads should be forbidden.
@@ -482,13 +480,13 @@ class FuncTest(BaseTest):
         self.assertEqual(text.strip("a"), "")
 
 def test_main():
-    test_support.run_unittest(
+    support.run_unittest(
         BZ2FileTest,
         BZ2CompressorTest,
         BZ2DecompressorTest,
         FuncTest
     )
-    test_support.reap_children()
+    support.reap_children()
 
 if __name__ == '__main__':
     test_main()
index 40fb76d..5692642 100644 (file)
@@ -2,11 +2,22 @@ import calendar
 import unittest
 
 from test import test_support
+from test.script_helper import assert_python_ok, assert_python_failure
 import locale
 import datetime
+import os
+
+result_2004_01_text = """\
+    January 2004
+Mo Tu We Th Fr Sa Su
+          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
+"""
 
-
-result_2004_text = """
+result_2004_text = """\
                                   2004
 
       January                   February                   March
@@ -44,7 +55,7 @@ Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
 25 26 27 28 29 30 31      29 30                     27 28 29 30 31
 """
 
-result_2004_html = """
+result_2004_html = """\
 <?xml version="1.0" encoding="ascii"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html>
@@ -460,6 +471,127 @@ class LeapdaysTestCase(unittest.TestCase):
         self.assertEqual(calendar.leapdays(1997,2020), 5)
 
 
+def conv(s):
+    return s.replace('\n', os.linesep)
+
+class CommandLineTestCase(unittest.TestCase):
+    def run_ok(self, *args):
+        return assert_python_ok('-m', 'calendar', *args)[1]
+
+    def assertFailure(self, *args):
+        rc, stdout, stderr = assert_python_failure('-m', 'calendar', *args)
+        self.assertIn(b'Usage:', stderr)
+        self.assertEqual(rc, 2)
+
+    def test_help(self):
+        stdout = self.run_ok('-h')
+        self.assertIn(b'Usage:', stdout)
+        self.assertIn(b'calendar.py', stdout)
+        self.assertIn(b'--help', stdout)
+
+    def test_illegal_arguments(self):
+        self.assertFailure('-z')
+        #self.assertFailure('spam')
+        #self.assertFailure('2004', 'spam')
+        self.assertFailure('-t', 'html', '2004', '1')
+
+    def test_output_current_year(self):
+        stdout = self.run_ok()
+        year = datetime.datetime.now().year
+        self.assertIn((' %s' % year).encode(), stdout)
+        self.assertIn(b'January', stdout)
+        self.assertIn(b'Mo Tu We Th Fr Sa Su', stdout)
+
+    def test_output_year(self):
+        stdout = self.run_ok('2004')
+        self.assertEqual(stdout.strip(), conv(result_2004_text).strip())
+
+    def test_output_month(self):
+        stdout = self.run_ok('2004', '1')
+        self.assertEqual(stdout.strip(), conv(result_2004_01_text).strip())
+
+    def test_option_encoding(self):
+        self.assertFailure('-e')
+        self.assertFailure('--encoding')
+        stdout = self.run_ok('--encoding', 'rot-13', '2004')
+        self.assertEqual(stdout.strip(), conv(result_2004_text.encode('rot-13')).strip())
+
+    def test_option_locale(self):
+        self.assertFailure('-L')
+        self.assertFailure('--locale')
+        self.assertFailure('-L', 'en')
+        lang, enc = locale.getdefaultlocale()
+        lang = lang or 'C'
+        enc = enc or 'UTF-8'
+        try:
+            oldlocale = locale.getlocale(locale.LC_TIME)
+            try:
+                locale.setlocale(locale.LC_TIME, (lang, enc))
+            finally:
+                locale.setlocale(locale.LC_TIME, oldlocale)
+        except (locale.Error, ValueError):
+            self.skipTest('cannot set the system default locale')
+        stdout = self.run_ok('--locale', lang, '--encoding', enc, '2004')
+        self.assertIn('2004'.encode(enc), stdout)
+
+    def test_option_width(self):
+        self.assertFailure('-w')
+        self.assertFailure('--width')
+        self.assertFailure('-w', 'spam')
+        stdout = self.run_ok('--width', '3', '2004')
+        self.assertIn(b'Mon Tue Wed Thu Fri Sat Sun', stdout)
+
+    def test_option_lines(self):
+        self.assertFailure('-l')
+        self.assertFailure('--lines')
+        self.assertFailure('-l', 'spam')
+        stdout = self.run_ok('--lines', '2', '2004')
+        self.assertIn(conv('December\n\nMo Tu We'), stdout)
+
+    def test_option_spacing(self):
+        self.assertFailure('-s')
+        self.assertFailure('--spacing')
+        self.assertFailure('-s', 'spam')
+        stdout = self.run_ok('--spacing', '8', '2004')
+        self.assertIn(b'Su        Mo', stdout)
+
+    def test_option_months(self):
+        self.assertFailure('-m')
+        self.assertFailure('--month')
+        self.assertFailure('-m', 'spam')
+        stdout = self.run_ok('--months', '1', '2004')
+        self.assertIn(conv('\nMo Tu We Th Fr Sa Su\n'), stdout)
+
+    def test_option_type(self):
+        self.assertFailure('-t')
+        self.assertFailure('--type')
+        self.assertFailure('-t', 'spam')
+        stdout = self.run_ok('--type', 'text', '2004')
+        self.assertEqual(stdout.strip(), conv(result_2004_text).strip())
+        stdout = self.run_ok('--type', 'html', '2004')
+        self.assertEqual(stdout[:6], b'<?xml ')
+        self.assertIn(b'<title>Calendar for 2004</title>', stdout)
+
+    def test_html_output_current_year(self):
+        stdout = self.run_ok('--type', 'html')
+        year = datetime.datetime.now().year
+        self.assertIn(('<title>Calendar for %s</title>' % year).encode(),
+                      stdout)
+        self.assertIn(b'<tr><th colspan="7" class="month">January</th></tr>',
+                      stdout)
+
+    def test_html_output_year_encoding(self):
+        stdout = self.run_ok('-t', 'html', '--encoding', 'ascii', '2004')
+        self.assertEqual(stdout.strip(), conv(result_2004_html).strip())
+
+    def test_html_output_year_css(self):
+        self.assertFailure('-t', 'html', '-c')
+        self.assertFailure('-t', 'html', '--css')
+        stdout = self.run_ok('-t', 'html', '--css', 'custom.css', '2004')
+        self.assertIn(b'<link rel="stylesheet" type="text/css" '
+                      b'href="custom.css" />', stdout)
+
+
 def test_main():
     test_support.run_unittest(
         OutputTestCase,
@@ -468,8 +600,10 @@ def test_main():
         SundayTestCase,
         MonthRangeTestCase,
         LeapdaysTestCase,
+        CommandLineTestCase,
     )
 
 
 if __name__ == "__main__":
     test_main()
+    unittest.main()
index a2cb5c7..2029265 100644 (file)
@@ -6,7 +6,7 @@ import sys
 import time
 import random
 import unittest
-from test import test_support
+from test import test_support as support
 try:
     import thread
     import threading
@@ -14,7 +14,7 @@ except ImportError:
     thread = None
     threading = None
 # Skip this test if the _testcapi module isn't available.
-_testcapi = test_support.import_module('_testcapi')
+_testcapi = support.import_module('_testcapi')
 
 
 @unittest.skipUnless(threading, 'Threading required for this test.')
@@ -42,7 +42,7 @@ class TestPendingCalls(unittest.TestCase):
             #this busy loop is where we expect to be interrupted to
             #run our callbacks.  Note that callbacks are only run on the
             #main thread
-            if False and test_support.verbose:
+            if False and support.verbose:
                 print "(%i)"%(len(l),),
             for i in xrange(1000):
                 a = i*i
@@ -51,7 +51,7 @@ class TestPendingCalls(unittest.TestCase):
             count += 1
             self.assertTrue(count < 10000,
                 "timeout waiting for %i callbacks, got %i"%(n, len(l)))
-        if False and test_support.verbose:
+        if False and support.verbose:
             print "(%i)"%(len(l),)
 
     def test_pendingcalls_threaded(self):
@@ -67,15 +67,11 @@ class TestPendingCalls(unittest.TestCase):
         context.lock = threading.Lock()
         context.event = threading.Event()
 
-        for i in range(context.nThreads):
-            t = threading.Thread(target=self.pendingcalls_thread, args = (context,))
-            t.start()
-            threads.append(t)
-
-        self.pendingcalls_wait(context.l, n, context)
-
-        for t in threads:
-            t.join()
+        threads = [threading.Thread(target=self.pendingcalls_thread,
+                                    args=(context,))
+                   for i in range(context.nThreads)]
+        with support.start_threads(threads):
+            self.pendingcalls_wait(context.l, n, context)
 
     def pendingcalls_thread(self, context):
         try:
@@ -84,7 +80,7 @@ class TestPendingCalls(unittest.TestCase):
             with context.lock:
                 context.nFinished += 1
                 nFinished = context.nFinished
-                if False and test_support.verbose:
+                if False and support.verbose:
                     print "finished threads: ", nFinished
             if nFinished == context.nThreads:
                 context.event.set()
@@ -103,7 +99,7 @@ class TestPendingCalls(unittest.TestCase):
 @unittest.skipUnless(threading and thread, 'Threading required for this test.')
 class TestThreadState(unittest.TestCase):
 
-    @test_support.reap_threads
+    @support.reap_threads
     def test_thread_state(self):
         # some extra thread-state tests driven via _testcapi
         def target():
@@ -129,14 +125,14 @@ def test_main():
     for name in dir(_testcapi):
         if name.startswith('test_'):
             test = getattr(_testcapi, name)
-            if test_support.verbose:
+            if support.verbose:
                 print "internal", name
             try:
                 test()
             except _testcapi.error:
-                raise test_support.TestFailed, sys.exc_info()[1]
+                raise support.TestFailed, sys.exc_info()[1]
 
-    test_support.run_unittest(TestPendingCalls, TestThreadState)
+    support.run_unittest(TestPendingCalls, TestThreadState)
 
 if __name__ == "__main__":
     test_main()
index df65f6e..906e9cf 100644 (file)
@@ -614,88 +614,96 @@ class ExceptionPicklingTestCase(unittest.TestCase):
     def test_error(self):
         import pickle
         e1 = ConfigParser.Error('value')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_nosectionerror(self):
         import pickle
         e1 = ConfigParser.NoSectionError('section')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_nooptionerror(self):
         import pickle
         e1 = ConfigParser.NoOptionError('option', 'section')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(e1.option, e2.option)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(e1.option, e2.option)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_duplicatesectionerror(self):
         import pickle
         e1 = ConfigParser.DuplicateSectionError('section')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_interpolationerror(self):
         import pickle
         e1 = ConfigParser.InterpolationError('option', 'section', 'msg')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(e1.option, e2.option)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(e1.option, e2.option)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_interpolationmissingoptionerror(self):
         import pickle
         e1 = ConfigParser.InterpolationMissingOptionError('option', 'section',
             'rawval', 'reference')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(e1.option, e2.option)
-        self.assertEqual(e1.reference, e2.reference)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(e1.option, e2.option)
+            self.assertEqual(e1.reference, e2.reference)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_interpolationsyntaxerror(self):
         import pickle
         e1 = ConfigParser.InterpolationSyntaxError('option', 'section', 'msg')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(e1.option, e2.option)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(e1.option, e2.option)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_interpolationdeptherror(self):
         import pickle
         e1 = ConfigParser.InterpolationDepthError('option', 'section',
             'rawval')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.section, e2.section)
-        self.assertEqual(e1.option, e2.option)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.section, e2.section)
+            self.assertEqual(e1.option, e2.option)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_parsingerror(self):
         import pickle
@@ -703,25 +711,27 @@ class ExceptionPicklingTestCase(unittest.TestCase):
         e1.append(1, 'line1')
         e1.append(2, 'line2')
         e1.append(3, 'line3')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.filename, e2.filename)
-        self.assertEqual(e1.errors, e2.errors)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.filename, e2.filename)
+            self.assertEqual(e1.errors, e2.errors)
+            self.assertEqual(repr(e1), repr(e2))
 
     def test_missingsectionheadererror(self):
         import pickle
         e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line')
-        pickled = pickle.dumps(e1)
-        e2 = pickle.loads(pickled)
-        self.assertEqual(e1.message, e2.message)
-        self.assertEqual(e1.args, e2.args)
-        self.assertEqual(e1.line, e2.line)
-        self.assertEqual(e1.filename, e2.filename)
-        self.assertEqual(e1.lineno, e2.lineno)
-        self.assertEqual(repr(e1), repr(e2))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            pickled = pickle.dumps(e1, proto)
+            e2 = pickle.loads(pickled)
+            self.assertEqual(e1.message, e2.message)
+            self.assertEqual(e1.args, e2.args)
+            self.assertEqual(e1.line, e2.line)
+            self.assertEqual(e1.filename, e2.filename)
+            self.assertEqual(e1.lineno, e2.lineno)
+            self.assertEqual(repr(e1), repr(e2))
 
 
 def test_main():
index dbdb4f4..b9cd9c2 100644 (file)
@@ -441,6 +441,16 @@ class CodecCallbackTest(unittest.TestCase):
             codecs.strict_errors,
             UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")
         )
+        self.assertRaises(
+            UnicodeDecodeError,
+            codecs.strict_errors,
+            UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")
+        )
+        self.assertRaises(
+            UnicodeTranslateError,
+            codecs.strict_errors,
+            UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
+        )
 
     def test_badandgoodignoreexceptions(self):
         # "ignore" complains about a non-exception passed in
@@ -457,16 +467,19 @@ class CodecCallbackTest(unittest.TestCase):
         )
         # If the correct exception is passed in, "ignore" returns an empty replacement
         self.assertEqual(
-            codecs.ignore_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
-            (u"", 1)
+            codecs.ignore_errors(
+                UnicodeEncodeError("ascii", u"a\u3042b", 1, 2, "ouch")),
+            (u"", 2)
         )
         self.assertEqual(
-            codecs.ignore_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
-            (u"", 1)
+            codecs.ignore_errors(
+                UnicodeDecodeError("ascii", "a\xffb", 1, 2, "ouch")),
+            (u"", 2)
         )
         self.assertEqual(
-            codecs.ignore_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
-            (u"", 1)
+            codecs.ignore_errors(
+                UnicodeTranslateError(u"a\u3042b", 1, 2, "ouch")),
+            (u"", 2)
         )
 
     def test_badandgoodreplaceexceptions(self):
@@ -494,16 +507,19 @@ class CodecCallbackTest(unittest.TestCase):
         )
         # With the correct exception, "replace" returns an "?" or u"\ufffd" replacement
         self.assertEqual(
-            codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
-            (u"?", 1)
+            codecs.replace_errors(
+                UnicodeEncodeError("ascii", u"a\u3042b", 1, 2, "ouch")),
+            (u"?", 2)
         )
         self.assertEqual(
-            codecs.replace_errors(UnicodeDecodeError("ascii", "\xff", 0, 1, "ouch")),
-            (u"\ufffd", 1)
+            codecs.replace_errors(
+                UnicodeDecodeError("ascii", "a\xffb", 1, 2, "ouch")),
+            (u"\ufffd", 2)
         )
         self.assertEqual(
-            codecs.replace_errors(UnicodeTranslateError(u"\u3042", 0, 1, "ouch")),
-            (u"\ufffd", 1)
+            codecs.replace_errors(
+                UnicodeTranslateError(u"a\u3042b", 1, 2, "ouch")),
+            (u"\ufffd", 2)
         )
 
     def test_badandgoodxmlcharrefreplaceexceptions(self):
@@ -531,13 +547,17 @@ class CodecCallbackTest(unittest.TestCase):
             UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
         )
         # Use the correct exception
-        cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042)
-        s = "".join(unichr(c) for c in cs)
+        cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000)
+        cs += (0xdfff, 0xd800)
+        s = u"".join(unichr(c) for c in cs)
+        s += u"\U0001869f\U000186a0\U000f423f\U000f4240"
+        cs += (99999, 100000, 999999, 1000000)
         self.assertEqual(
             codecs.xmlcharrefreplace_errors(
-                UnicodeEncodeError("ascii", s, 0, len(s), "ouch")
+                UnicodeEncodeError("ascii", u"a" + s + u"b",
+                                   1, 1 + len(s), "ouch")
             ),
-            (u"".join(u"&#%d;" % ord(c) for c in s), len(s))
+            (u"".join(u"&#%d;" % c for c in cs), 1 + len(s))
         )
 
     def test_badandgoodbackslashreplaceexceptions(self):
@@ -565,34 +585,34 @@ class CodecCallbackTest(unittest.TestCase):
             UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
         )
         # Use the correct exception
-        self.assertEqual(
-            codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
-            (u"\\u3042", 1)
-        )
-        self.assertEqual(
-            codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\x00", 0, 1, "ouch")),
-            (u"\\x00", 1)
-        )
-        self.assertEqual(
-            codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\xff", 0, 1, "ouch")),
-            (u"\\xff", 1)
-        )
-        self.assertEqual(
-            codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\u0100", 0, 1, "ouch")),
-            (u"\\u0100", 1)
-        )
-        self.assertEqual(
-            codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\uffff", 0, 1, "ouch")),
-            (u"\\uffff", 1)
-        )
-        if sys.maxunicode>0xffff:
-            self.assertEqual(
-                codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U00010000", 0, 1, "ouch")),
-                (u"\\U00010000", 1)
-            )
+        tests = [
+            (u"\u3042", u"\\u3042"),
+            (u"\n", u"\\x0a"),
+            (u"a", u"\\x61"),
+            (u"\x00", u"\\x00"),
+            (u"\xff", u"\\xff"),
+            (u"\u0100", u"\\u0100"),
+            (u"\uffff", u"\\uffff"),
+            # Lone surrogates
+            (u"\ud800", u"\\ud800"),
+            (u"\udfff", u"\\udfff"),
+        ]
+        if sys.maxunicode > 0xffff:
+            tests += [
+                (u"\U00010000", u"\\U00010000"),
+                (u"\U0010ffff", u"\\U0010ffff"),
+            ]
+        else:
+            tests += [
+                (u"\U00010000", u"\\ud800\\udc00"),
+                (u"\U0010ffff", u"\\udbff\\udfff"),
+            ]
+        for s, r in tests:
             self.assertEqual(
-                codecs.backslashreplace_errors(UnicodeEncodeError("ascii", u"\U0010ffff", 0, 1, "ouch")),
-                (u"\\U0010ffff", 1)
+                codecs.backslashreplace_errors(
+                    UnicodeEncodeError("ascii", u"a" + s + u"b",
+                                       1, 1 + len(s), "ouch")),
+                (r, 1 + len(s))
             )
 
     def test_badhandlerresults(self):
index 9f3b17a..de80b07 100644 (file)
@@ -1348,6 +1348,28 @@ class CodecsModuleTest(unittest.TestCase):
         c = codecs.lookup('ASCII')
         self.assertEqual(c.name, 'ascii')
 
+    def test_all(self):
+        api = (
+            "encode", "decode",
+            "register", "CodecInfo", "Codec", "IncrementalEncoder",
+            "IncrementalDecoder", "StreamReader", "StreamWriter", "lookup",
+            "getencoder", "getdecoder", "getincrementalencoder",
+            "getincrementaldecoder", "getreader", "getwriter",
+            "register_error", "lookup_error",
+            "strict_errors", "replace_errors", "ignore_errors",
+            "xmlcharrefreplace_errors", "backslashreplace_errors",
+            "open", "EncodedFile",
+            "iterencode", "iterdecode",
+            "BOM", "BOM_BE", "BOM_LE",
+            "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_BE", "BOM_UTF16_LE",
+            "BOM_UTF32", "BOM_UTF32_BE", "BOM_UTF32_LE",
+            "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",  # Undocumented
+            "StreamReaderWriter", "StreamRecoder",
+        )
+        self.assertEqual(sorted(api), sorted(codecs.__all__))
+        for api in codecs.__all__:
+            getattr(codecs, api)
+
 class StreamReaderTest(unittest.TestCase):
 
     def setUp(self):
index 20e0667..cd27227 100644 (file)
@@ -905,6 +905,28 @@ class TestCounter(unittest.TestCase):
         self.assertEqual(c.setdefault('e', 5), 5)
         self.assertEqual(c['e'], 5)
 
+    def test_init(self):
+        self.assertEqual(list(Counter(self=42).items()), [('self', 42)])
+        self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)])
+        self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)])
+        self.assertRaises(TypeError, Counter, 42)
+        self.assertRaises(TypeError, Counter, (), ())
+        self.assertRaises(TypeError, Counter.__init__)
+
+    def test_update(self):
+        c = Counter()
+        c.update(self=42)
+        self.assertEqual(list(c.items()), [('self', 42)])
+        c = Counter()
+        c.update(iterable=42)
+        self.assertEqual(list(c.items()), [('iterable', 42)])
+        c = Counter()
+        c.update(iterable=None)
+        self.assertEqual(list(c.items()), [('iterable', None)])
+        self.assertRaises(TypeError, Counter().update, 42)
+        self.assertRaises(TypeError, Counter().update, {}, {})
+        self.assertRaises(TypeError, Counter.update)
+
     def test_copying(self):
         # Check that counters are copyable, deepcopyable, picklable, and
         #have a repr/eval round-trip
@@ -1006,6 +1028,16 @@ class TestCounter(unittest.TestCase):
         c.subtract('aaaabbcce')
         self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
 
+        c = Counter()
+        c.subtract(self=42)
+        self.assertEqual(list(c.items()), [('self', -42)])
+        c = Counter()
+        c.subtract(iterable=42)
+        self.assertEqual(list(c.items()), [('iterable', -42)])
+        self.assertRaises(TypeError, Counter().subtract, 42)
+        self.assertRaises(TypeError, Counter().subtract, {}, {})
+        self.assertRaises(TypeError, Counter.subtract)
+
 class TestOrderedDict(unittest.TestCase):
 
     def test_init(self):
@@ -1019,8 +1051,11 @@ class TestOrderedDict(unittest.TestCase):
                                           c=3, e=5).items()), pairs)                # mixed input
 
         # make sure no positional args conflict with possible kwdargs
-        self.assertEqual(inspect.getargspec(OrderedDict.__dict__['__init__']).args,
-                         ['self'])
+        self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)])
+        self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)])
+        self.assertRaises(TypeError, OrderedDict, 42)
+        self.assertRaises(TypeError, OrderedDict, (), ())
+        self.assertRaises(TypeError, OrderedDict.__init__)
 
         # Make sure that direct calls to __init__ do not clear previous contents
         d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
@@ -1065,6 +1100,10 @@ class TestOrderedDict(unittest.TestCase):
         self.assertEqual(list(d.items()),
             [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
 
+        self.assertRaises(TypeError, OrderedDict().update, 42)
+        self.assertRaises(TypeError, OrderedDict().update, (), ())
+        self.assertRaises(TypeError, OrderedDict.update)
+
     def test_abc(self):
         self.assertIsInstance(OrderedDict(), MutableMapping)
         self.assertTrue(issubclass(OrderedDict, MutableMapping))
index 36cd52e..4041901 100644 (file)
@@ -27,6 +27,20 @@ class CookieTests(unittest.TestCase):
               'dict': {'keebler' : 'E=mc2'},
               'repr': "<SimpleCookie: keebler='E=mc2'>",
               'output': 'Set-Cookie: keebler=E=mc2',
+            },
+
+            # issue22931 - Adding '[' and ']' as valid characters in cookie
+            # values as defined in RFC 6265
+            {
+                'data': 'a=b; c=[; d=r; f=h',
+                'dict': {'a':'b', 'c':'[', 'd':'r', 'f':'h'},
+                'repr': "<SimpleCookie: a='b' c='[' d='r' f='h'>",
+                'output': '\n'.join((
+                    'Set-Cookie: a=b',
+                    'Set-Cookie: c=[',
+                    'Set-Cookie: d=r',
+                    'Set-Cookie: f=h'
+                ))
             }
         ]
 
index d4b80fa..d272d12 100644 (file)
@@ -445,6 +445,9 @@ class CookieTests(TestCase):
         interact_netscape(c, "http://www.acme.com:80/", 'foo=bar; expires=')
         interact_netscape(c, "http://www.acme.com:80/", 'spam=eggs; '
                           'expires="Foo Bar 25 33:22:11 3022"')
+        interact_netscape(c, 'http://www.acme.com/', 'fortytwo=')
+        interact_netscape(c, 'http://www.acme.com/', '=unladenswallow')
+        interact_netscape(c, 'http://www.acme.com/', 'holyhandgrenade')
 
         cookie = c._cookies[".acme.com"]["/"]["spam"]
         self.assertEqual(cookie.domain, ".acme.com")
@@ -471,6 +474,16 @@ class CookieTests(TestCase):
         self.assertIsNone(foo.expires)
         self.assertIsNone(spam.expires)
 
+        cookie = c._cookies['www.acme.com']['/']['fortytwo']
+        self.assertIsNotNone(cookie.value)
+        self.assertEqual(cookie.value, '')
+
+        # there should be a distinction between a present but empty value
+        # (above) and a value that's entirely missing (below)
+
+        cookie = c._cookies['www.acme.com']['/']['holyhandgrenade']
+        self.assertIsNone(cookie.value)
+
     def test_ns_parser_special_names(self):
         # names such as 'expires' are not special in first name=value pair
         # of Set-Cookie: header
@@ -1092,6 +1105,13 @@ class CookieTests(TestCase):
             parse_ns_headers(["foo"]),
             [[("foo", None), ("version", "0")]]
             )
+        # missing cookie values for parsed attributes
+        self.assertEqual(
+            parse_ns_headers(['foo=bar; expires']),
+            [[('foo', 'bar'), ('expires', None), ('version', '0')]])
+        self.assertEqual(
+            parse_ns_headers(['foo=bar; version']),
+            [[('foo', 'bar'), ('version', None)]])
         # shouldn't add version if header is empty
         self.assertEqual(parse_ns_headers([""]), [])
 
@@ -1106,6 +1126,8 @@ class CookieTests(TestCase):
             c.extract_cookies(r, req)
             return c
 
+        future = cookielib.time2netscape(time.time()+3600)
+
         # none of these bad headers should cause an exception to be raised
         for headers in [
             ["Set-Cookie: "],  # actually, nothing wrong with this
@@ -1116,6 +1138,7 @@ class CookieTests(TestCase):
             ["Set-Cookie: b=foo; max-age=oops"],
             # bad version
             ["Set-Cookie: b=foo; version=spam"],
+            ["Set-Cookie:; Expires=%s" % future],
             ]:
             c = cookiejar_from_cookie_headers(headers)
             # these bad cookies shouldn't be set
index e031170..e2eec70 100644 (file)
@@ -130,12 +130,24 @@ class Test_Csv(unittest.TestCase):
             fileobj.close()
             os.unlink(name)
 
+    def _write_error_test(self, exc, fields, **kwargs):
+        fd, name = tempfile.mkstemp()
+        fileobj = os.fdopen(fd, "w+b")
+        try:
+            writer = csv.writer(fileobj, **kwargs)
+            with self.assertRaises(exc):
+                writer.writerow(fields)
+            fileobj.seek(0)
+            self.assertEqual(fileobj.read(), '')
+        finally:
+            fileobj.close()
+            os.unlink(name)
+
     def test_write_arg_valid(self):
-        self.assertRaises(csv.Error, self._write_test, None, '')
+        self._write_error_test(csv.Error, None)
         self._write_test((), '')
         self._write_test([None], '""')
-        self.assertRaises(csv.Error, self._write_test,
-                          [None], None, quoting = csv.QUOTE_NONE)
+        self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE)
         # Check that exceptions are passed up the chain
         class BadList:
             def __len__(self):
@@ -143,11 +155,11 @@ class Test_Csv(unittest.TestCase):
             def __getitem__(self, i):
                 if i > 2:
                     raise IOError
-        self.assertRaises(IOError, self._write_test, BadList(), '')
+        self._write_error_test(IOError, BadList())
         class BadItem:
             def __str__(self):
                 raise IOError
-        self.assertRaises(IOError, self._write_test, [BadItem()], '')
+        self._write_error_test(IOError, [BadItem()])
 
     def test_write_bigfield(self):
         # This exercises the buffer realloc functionality
@@ -157,10 +169,8 @@ class Test_Csv(unittest.TestCase):
 
     def test_write_quoting(self):
         self._write_test(['a',1,'p,q'], 'a,1,"p,q"')
-        self.assertRaises(csv.Error,
-                          self._write_test,
-                          ['a',1,'p,q'], 'a,1,p,q',
-                          quoting = csv.QUOTE_NONE)
+        self._write_error_test(csv.Error, ['a',1,'p,q'],
+                               quoting = csv.QUOTE_NONE)
         self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
                          quoting = csv.QUOTE_MINIMAL)
         self._write_test(['a',1,'p,q'], '"a",1,"p,q"',
@@ -173,10 +183,8 @@ class Test_Csv(unittest.TestCase):
     def test_write_escape(self):
         self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
                          escapechar='\\')
-        self.assertRaises(csv.Error,
-                          self._write_test,
-                          ['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
-                          escapechar=None, doublequote=False)
+        self._write_error_test(csv.Error, ['a',1,'p,"q"'],
+                               escapechar=None, doublequote=False)
         self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
                          escapechar='\\', doublequote = False)
         self._write_test(['"'], '""""',
index 7caa408..19ffbcd 100644 (file)
@@ -1421,11 +1421,12 @@ class TestDateTime(TestDate):
 
     def test_more_pickling(self):
         a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
-        s = pickle.dumps(a)
-        b = pickle.loads(s)
-        self.assertEqual(b.year, 2003)
-        self.assertEqual(b.month, 2)
-        self.assertEqual(b.day, 7)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            s = pickle.dumps(a, proto)
+            b = pickle.loads(s)
+            self.assertEqual(b.year, 2003)
+            self.assertEqual(b.month, 2)
+            self.assertEqual(b.day, 7)
 
     def test_pickling_subclass_datetime(self):
         args = 6, 7, 23, 20, 59, 1, 64**2
index 4dbe62d..3b3d9d1 100644 (file)
@@ -32,7 +32,8 @@ import unittest
 from decimal import *
 import numbers
 from test.test_support import (run_unittest, run_doctest, requires_unicode, u,
-                               is_resource_enabled, check_py3k_warnings)
+                               is_resource_enabled, check_py3k_warnings,
+                               run_with_locale)
 import random
 try:
     import threading
@@ -905,6 +906,23 @@ class DecimalFormatTest(unittest.TestCase):
         self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6')
         self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6')
 
+    @run_with_locale('LC_ALL', 'ps_AF.UTF-8')
+    def test_wide_char_separator_decimal_point(self):
+        # locale with wide char separator and decimal point
+        import locale
+
+        decimal_point = locale.localeconv()['decimal_point']
+        thousands_sep = locale.localeconv()['thousands_sep']
+        if decimal_point != '\xd9\xab':
+            self.skipTest('inappropriate decimal point separator'
+                          '({!r} not {!r})'.format(decimal_point, '\xd9\xab'))
+        if thousands_sep != '\xd9\xac':
+            self.skipTest('inappropriate thousands separator'
+                          '({!r} not {!r})'.format(thousands_sep, '\xd9\xac'))
+
+        self.assertEqual(format(Decimal('100000000.123'), 'n'),
+                         '100\xd9\xac000\xd9\xac000\xd9\xab123')
+
 
 class DecimalArithmeticOperatorsTest(unittest.TestCase):
     '''Unit tests for all arithmetic operators, binary and unary.'''
@@ -1664,9 +1682,10 @@ class DecimalPythonAPItests(unittest.TestCase):
 
     def test_pickle(self):
         d = Decimal('-3.141590000')
-        p = pickle.dumps(d)
-        e = pickle.loads(p)
-        self.assertEqual(d, e)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            p = pickle.dumps(d, proto)
+            e = pickle.loads(p)
+            self.assertEqual(d, e)
 
     def test_int(self):
         for x in range(-250, 250):
@@ -1750,12 +1769,13 @@ class DecimalPythonAPItests(unittest.TestCase):
 class ContextAPItests(unittest.TestCase):
 
     def test_pickle(self):
-        c = Context()
-        e = pickle.loads(pickle.dumps(c))
-        for k in vars(c):
-            v1 = vars(c)[k]
-            v2 = vars(e)[k]
-            self.assertEqual(v1, v2)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            c = Context()
+            e = pickle.loads(pickle.dumps(c, proto))
+            for k in vars(c):
+                v1 = vars(c)[k]
+                v2 = vars(e)[k]
+                self.assertEqual(v1, v2)
 
     def test_equality_with_other_types(self):
         self.assertIn(Decimal(10), ['a', 1.0, Decimal(10), (1,2), {}])
index 595a0c4..13ea02f 100644 (file)
@@ -600,11 +600,12 @@ class TestSubclass(unittest.TestCase):
         self.assertEqual(type(d), type(e))
         self.assertEqual(list(d), list(e))
 
-        s = pickle.dumps(d)
-        e = pickle.loads(s)
-        self.assertNotEqual(id(d), id(e))
-        self.assertEqual(type(d), type(e))
-        self.assertEqual(list(d), list(e))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            s = pickle.dumps(d, proto)
+            e = pickle.loads(s)
+            self.assertNotEqual(id(d), id(e))
+            self.assertEqual(type(d), type(e))
+            self.assertEqual(list(d), list(e))
 
         d = Deque('abcde', maxlen=4)
 
@@ -616,11 +617,12 @@ class TestSubclass(unittest.TestCase):
         self.assertEqual(type(d), type(e))
         self.assertEqual(list(d), list(e))
 
-        s = pickle.dumps(d)
-        e = pickle.loads(s)
-        self.assertNotEqual(id(d), id(e))
-        self.assertEqual(type(d), type(e))
-        self.assertEqual(list(d), list(e))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            s = pickle.dumps(d, proto)
+            e = pickle.loads(s)
+            self.assertNotEqual(id(d), id(e))
+            self.assertEqual(type(d), type(e))
+            self.assertEqual(list(d), list(e))
 
 ##    def test_pickle(self):
 ##        d = Deque('abc')
index 6f91842..0ac458f 100644 (file)
@@ -2066,7 +2066,7 @@ order (MRO) for bases """
                                  "attr on a property" % attr)
 
         class D(object):
-            __getitem__ = property(lambda s: 1/0)
+            __getitem__ = property(lambda s: 1.0/0.0)
 
         d = D()
         try:
@@ -3300,7 +3300,7 @@ order (MRO) for bases """
             pass
 
         for p in pickle, cPickle:
-            for bin in 0, 1:
+            for bin in range(p.HIGHEST_PROTOCOL + 1):
                 for cls in C, C1, C2:
                     s = p.dumps(cls, bin)
                     cls2 = p.loads(s)
@@ -3358,30 +3358,31 @@ order (MRO) for bases """
                 __slots__ = ['a']
             class D(C):
                 pass
-            try:
-                pickle.dumps(C())
-            except TypeError:
-                pass
-            else:
-                self.fail("should fail: pickle C instance - %s" % base)
-            try:
-                cPickle.dumps(C())
-            except TypeError:
-                pass
-            else:
-                self.fail("should fail: cPickle C instance - %s" % base)
-            try:
-                pickle.dumps(C())
-            except TypeError:
-                pass
-            else:
-                self.fail("should fail: pickle D instance - %s" % base)
-            try:
-                cPickle.dumps(D())
-            except TypeError:
-                pass
-            else:
-                self.fail("should fail: cPickle D instance - %s" % base)
+            for proto in range(2):
+                try:
+                    pickle.dumps(C(), proto)
+                except TypeError:
+                    pass
+                else:
+                    self.fail("should fail: pickle C instance - %s" % base)
+                try:
+                    cPickle.dumps(C(), proto)
+                except TypeError:
+                    pass
+                else:
+                    self.fail("should fail: cPickle C instance - %s" % base)
+                try:
+                    pickle.dumps(C(), proto)
+                except TypeError:
+                    pass
+                else:
+                    self.fail("should fail: pickle D instance - %s" % base)
+                try:
+                    cPickle.dumps(D(), proto)
+                except TypeError:
+                    pass
+                else:
+                    self.fail("should fail: cPickle D instance - %s" % base)
             # Give C a nice generic __getstate__ and __setstate__
             class C(base):
                 __slots__ = ['a']
@@ -3404,34 +3405,38 @@ order (MRO) for bases """
                 pass
             # Now it should work
             x = C()
-            y = pickle.loads(pickle.dumps(x))
-            self.assertNotHasAttr(y, 'a')
-            y = cPickle.loads(cPickle.dumps(x))
-            self.assertNotHasAttr(y, 'a')
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                y = pickle.loads(pickle.dumps(x, proto))
+                self.assertNotHasAttr(y, 'a')
+                y = cPickle.loads(cPickle.dumps(x, proto))
+                self.assertNotHasAttr(y, 'a')
             x.a = 42
-            y = pickle.loads(pickle.dumps(x))
-            self.assertEqual(y.a, 42)
-            y = cPickle.loads(cPickle.dumps(x))
-            self.assertEqual(y.a, 42)
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                y = pickle.loads(pickle.dumps(x, proto))
+                self.assertEqual(y.a, 42)
+                y = cPickle.loads(cPickle.dumps(x, proto))
+                self.assertEqual(y.a, 42)
             x = D()
             x.a = 42
             x.b = 100
-            y = pickle.loads(pickle.dumps(x))
-            self.assertEqual(y.a + y.b, 142)
-            y = cPickle.loads(cPickle.dumps(x))
-            self.assertEqual(y.a + y.b, 142)
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                y = pickle.loads(pickle.dumps(x, proto))
+                self.assertEqual(y.a + y.b, 142)
+                y = cPickle.loads(cPickle.dumps(x, proto))
+                self.assertEqual(y.a + y.b, 142)
             # A subclass that adds a slot should also work
             class E(C):
                 __slots__ = ['b']
             x = E()
             x.a = 42
             x.b = "foo"
-            y = pickle.loads(pickle.dumps(x))
-            self.assertEqual(y.a, x.a)
-            self.assertEqual(y.b, x.b)
-            y = cPickle.loads(cPickle.dumps(x))
-            self.assertEqual(y.a, x.a)
-            self.assertEqual(y.b, x.b)
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                y = pickle.loads(pickle.dumps(x, proto))
+                self.assertEqual(y.a, x.a)
+                self.assertEqual(y.b, x.b)
+                y = cPickle.loads(cPickle.dumps(x, proto))
+                self.assertEqual(y.a, x.a)
+                self.assertEqual(y.b, x.b)
 
     def test_binary_operator_override(self):
         # Testing overrides of binary operations...
index 07a2997..c1e4c13 100644 (file)
@@ -2580,7 +2580,8 @@ Windows line endings first:
 
     >>> import tempfile, os
     >>> fn = tempfile.mktemp()
-    >>> open(fn, 'w').write('Test:\r\n\r\n  >>> x = 1 + 1\r\n\r\nDone.\r\n')
+    >>> with open(fn, 'wb') as f:
+    ...     f.write('Test:\r\n\r\n  >>> x = 1 + 1\r\n\r\nDone.\r\n')
     >>> doctest.testfile(fn, False)
     TestResults(failed=0, attempted=1)
     >>> os.remove(fn)
@@ -2588,7 +2589,8 @@ Windows line endings first:
 And now *nix line endings:
 
     >>> fn = tempfile.mktemp()
-    >>> open(fn, 'w').write('Test:\n\n  >>> x = 1 + 1\n\nDone.\n')
+    >>> with open(fn, 'wb') as f:
+    ...     f.write('Test:\n\n  >>> x = 1 + 1\n\nDone.\n')
     >>> doctest.testfile(fn, False)
     TestResults(failed=0, attempted=1)
     >>> os.remove(fn)
index 80d1803..a1a1fcf 100644 (file)
@@ -10,7 +10,7 @@ import unittest
 PORT = None
 
 def make_request_and_skipIf(condition, reason):
-    # If we skip the test, we have to make a request because the
+    # If we skip the test, we have to make a request because
     # the server created in setUp blocks expecting one to come in.
     if not condition:
         return lambda func: func
index 6f5324f..6520efd 100644 (file)
@@ -160,6 +160,14 @@ class DumbDBMTestCase(unittest.TestCase):
             self.assertEqual(expected, got)
             f.close()
 
+    def test_eval(self):
+        with open(_fname + '.dir', 'w') as stream:
+            stream.write("str(__import__('sys').stdout.write('Hacked!')), 0\n")
+        with test_support.captured_stdout() as stdout:
+            with self.assertRaises(ValueError):
+                dumbdbm.open(_fname).close()
+            self.assertEqual(stdout.getvalue(), '')
+
     def tearDown(self):
         _delete_files()
 
index dc02cb3..b950031 100644 (file)
@@ -92,7 +92,7 @@ class ExceptionTests(unittest.TestCase):
 
         self.raise_catch(TabError, "TabError")
         # can only be tested under -tt, and is the only test for -tt
-        #try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')
+        #try: compile("try:\n\t1.0/0.0\n    \t1.0/0.0\nfinally:\n pass\n", '<string>', 'exec')
         #except TabError: pass
         #else: self.fail("TabError not raised")
 
index 3803950..e39ef70 100644 (file)
@@ -4,6 +4,7 @@ import unittest
 import itertools
 import select
 import signal
+import stat
 import subprocess
 import time
 from array import array
@@ -230,14 +231,20 @@ class OtherFileTests(unittest.TestCase):
             else:
                 f.close()
 
-    def testStdin(self):
-        # This causes the interpreter to exit on OSF1 v5.1.
-        if sys.platform != 'osf1V5':
-            self.assertRaises(IOError, sys.stdin.seek, -1)
-        else:
-            print >>sys.__stdout__, (
-                '  Skipping sys.stdin.seek(-1), it may crash the interpreter.'
-                ' Test manually.')
+    def testStdinSeek(self):
+        if sys.platform == 'osf1V5':
+            # This causes the interpreter to exit on OSF1 v5.1.
+            self.skipTest('Skipping sys.stdin.seek(-1), it may crash '
+                          'the interpreter. Test manually.')
+
+        if not sys.stdin.isatty():
+            # Issue #23168: if stdin is redirected to a file, stdin becomes
+            # seekable
+            self.skipTest('stdin must be a TTY in this test')
+
+        self.assertRaises(IOError, sys.stdin.seek, -1)
+
+    def testStdinTruncate(self):
         self.assertRaises(IOError, sys.stdin.truncate)
 
     def testUnicodeOpen(self):
@@ -424,17 +431,22 @@ class OtherFileTests(unittest.TestCase):
 
     @unittest.skipUnless(os.name == 'posix', 'test requires a posix system.')
     def test_write_full(self):
-        # Issue #17976
-        try:
-            f = open('/dev/full', 'w', 1)
-        except IOError:
-            self.skipTest("requires '/dev/full'")
-        try:
+        devfull = '/dev/full'
+        if not (os.path.exists(devfull) and
+                stat.S_ISCHR(os.stat(devfull).st_mode)):
+            # Issue #21934: OpenBSD does not have a /dev/full character device
+            self.skipTest('requires %r' % devfull)
+        with open(devfull, 'wb', 1) as f:
+            with self.assertRaises(IOError):
+                f.write('hello\n')
+        with open(devfull, 'wb', 1) as f:
             with self.assertRaises(IOError):
+                # Issue #17976
                 f.write('hello')
                 f.write('\n')
-        finally:
-            f.close()
+        with open(devfull, 'wb', 0) as f:
+            with self.assertRaises(IOError):
+                f.write('h')
 
     @unittest.skipUnless(sys.maxsize > 2**31, "requires 64-bit system")
     @test_support.precisionbigmemtest(2**31, 2.5, dry_run=False)
index b45d79b..e21e47f 100644 (file)
@@ -125,9 +125,9 @@ class AutoFileTests(unittest.TestCase):
         self.assertTrue(f.closed)
 
     def testMethods(self):
-        methods = ['fileno', 'isatty', 'read', 'readinto',
-                   'seek', 'tell', 'truncate', 'write', 'seekable',
-                   'readable', 'writable']
+        methods = ['fileno', 'isatty', 'seekable', 'readable', 'writable',
+                   'read', 'readall', 'readline', 'readlines',
+                   'tell', 'truncate', 'flush']
         if sys.platform.startswith('atheos'):
             methods.remove('truncate')
 
@@ -139,6 +139,15 @@ class AutoFileTests(unittest.TestCase):
             # should raise on closed file
             self.assertRaises(ValueError, method)
 
+        self.assertRaises(ValueError, self.f.readinto) # XXX should be TypeError?
+        self.assertRaises(ValueError, self.f.readinto, bytearray(1))
+        self.assertRaises(ValueError, self.f.seek)
+        self.assertRaises(ValueError, self.f.seek, 0)
+        self.assertRaises(ValueError, self.f.write)
+        self.assertRaises(ValueError, self.f.write, b'')
+        self.assertRaises(TypeError, self.f.writelines)
+        self.assertRaises(ValueError, self.f.writelines, b'')
+
     def testOpendir(self):
         # Issue 3703: opening a directory should fill the errno
         # Windows always returns "[Errno 13]: Permission denied
index e6779c4..5bf1d31 100644 (file)
@@ -8,6 +8,7 @@ import operator
 import random
 import fractions
 import sys
+import time
 
 INF = float("inf")
 NAN = float("nan")
@@ -164,6 +165,11 @@ class GeneralFloatCases(unittest.TestCase):
         self.assertAlmostEqual(float(FooUnicode('8')), 9.)
         self.assertAlmostEqual(float(FooStr('8')), 9.)
 
+        class Foo5:
+            def __float__(self):
+                return ""
+        self.assertRaises(TypeError, time.sleep, Foo5())
+
     def test_is_integer(self):
         self.assertFalse((1.1).is_integer())
         self.assertTrue((1.).is_integer())
index 4c229c0..cc1c19b 100644 (file)
@@ -20,7 +20,7 @@ from test import test_support
 from test.test_support import HOST, HOSTv6
 threading = test_support.import_module('threading')
 
-
+TIMEOUT = 3
 # the dummy data returned by server over the data channel when
 # RETR, LIST and NLST commands are issued
 RETR_DATA = 'abcde12345\r\n' * 1000
@@ -223,6 +223,7 @@ class DummyFTPServer(asyncore.dispatcher, threading.Thread):
         self.active = False
         self.active_lock = threading.Lock()
         self.host, self.port = self.socket.getsockname()[:2]
+        self.handler_instance = None
 
     def start(self):
         assert not self.active
@@ -246,8 +247,7 @@ class DummyFTPServer(asyncore.dispatcher, threading.Thread):
 
     def handle_accept(self):
         conn, addr = self.accept()
-        self.handler = self.handler(conn)
-        self.close()
+        self.handler_instance = self.handler(conn)
 
     def handle_connect(self):
         self.close()
@@ -262,7 +262,8 @@ class DummyFTPServer(asyncore.dispatcher, threading.Thread):
 
 if ssl is not None:
 
-    CERTFILE = os.path.join(os.path.dirname(__file__), "keycert.pem")
+    CERTFILE = os.path.join(os.path.dirname(__file__), "keycert3.pem")
+    CAFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem")
 
     class SSLConnection(object, asyncore.dispatcher):
         """An asyncore.dispatcher subclass supporting TLS/SSL."""
@@ -271,23 +272,25 @@ if ssl is not None:
         _ssl_closing = False
 
         def secure_connection(self):
-            self.socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
-                                          certfile=CERTFILE, server_side=True,
-                                          do_handshake_on_connect=False,
-                                          ssl_version=ssl.PROTOCOL_SSLv23)
+            socket = ssl.wrap_socket(self.socket, suppress_ragged_eofs=False,
+                                     certfile=CERTFILE, server_side=True,
+                                     do_handshake_on_connect=False,
+                                     ssl_version=ssl.PROTOCOL_SSLv23)
+            self.del_channel()
+            self.set_socket(socket)
             self._ssl_accepting = True
 
         def _do_ssl_handshake(self):
             try:
                 self.socket.do_handshake()
-            except ssl.SSLError, err:
+            except ssl.SSLError as err:
                 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                    ssl.SSL_ERROR_WANT_WRITE):
                     return
                 elif err.args[0] == ssl.SSL_ERROR_EOF:
                     return self.handle_close()
                 raise
-            except socket.error, err:
+            except socket.error as err:
                 if err.args[0] == errno.ECONNABORTED:
                     return self.handle_close()
             else:
@@ -297,18 +300,21 @@ if ssl is not None:
             self._ssl_closing = True
             try:
                 self.socket = self.socket.unwrap()
-            except ssl.SSLError, err:
+            except ssl.SSLError as err:
                 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                    ssl.SSL_ERROR_WANT_WRITE):
                     return
-            except socket.error, err:
+            except socket.error as err:
                 # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
                 # from OpenSSL's SSL_shutdown(), corresponding to a
                 # closed socket condition. See also:
                 # http://www.mail-archive.com/openssl-users@openssl.org/msg60710.html
                 pass
             self._ssl_closing = False
-            super(SSLConnection, self).close()
+            if getattr(self, '_ccc', False) is False:
+                super(SSLConnection, self).close()
+            else:
+                pass
 
         def handle_read_event(self):
             if self._ssl_accepting:
@@ -329,7 +335,7 @@ if ssl is not None:
         def send(self, data):
             try:
                 return super(SSLConnection, self).send(data)
-            except ssl.SSLError, err:
+            except ssl.SSLError as err:
                 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN,
                                    ssl.SSL_ERROR_WANT_READ,
                                    ssl.SSL_ERROR_WANT_WRITE):
@@ -339,13 +345,13 @@ if ssl is not None:
         def recv(self, buffer_size):
             try:
                 return super(SSLConnection, self).recv(buffer_size)
-            except ssl.SSLError, err:
+            except ssl.SSLError as err:
                 if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
                                    ssl.SSL_ERROR_WANT_WRITE):
-                    return ''
+                    return b''
                 if err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
                     self.handle_close()
-                    return ''
+                    return b''
                 raise
 
         def handle_error(self):
@@ -355,6 +361,8 @@ if ssl is not None:
             if (isinstance(self.socket, ssl.SSLSocket) and
                 self.socket._sslobj is not None):
                 self._do_ssl_shutdown()
+            else:
+                super(SSLConnection, self).close()
 
 
     class DummyTLS_DTPHandler(SSLConnection, DummyDTPHandler):
@@ -462,12 +470,12 @@ class TestFTPClass(TestCase):
 
     def test_rename(self):
         self.client.rename('a', 'b')
-        self.server.handler.next_response = '200'
+        self.server.handler_instance.next_response = '200'
         self.assertRaises(ftplib.error_reply, self.client.rename, 'a', 'b')
 
     def test_delete(self):
         self.client.delete('foo')
-        self.server.handler.next_response = '199'
+        self.server.handler_instance.next_response = '199'
         self.assertRaises(ftplib.error_reply, self.client.delete, 'foo')
 
     def test_size(self):
@@ -515,7 +523,7 @@ class TestFTPClass(TestCase):
     def test_storbinary(self):
         f = StringIO.StringIO(RETR_DATA)
         self.client.storbinary('stor', f)
-        self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
+        self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
         # test new callback arg
         flag = []
         f.seek(0)
@@ -527,12 +535,12 @@ class TestFTPClass(TestCase):
         for r in (30, '30'):
             f.seek(0)
             self.client.storbinary('stor', f, rest=r)
-            self.assertEqual(self.server.handler.rest, str(r))
+            self.assertEqual(self.server.handler_instance.rest, str(r))
 
     def test_storlines(self):
         f = StringIO.StringIO(RETR_DATA.replace('\r\n', '\n'))
         self.client.storlines('stor', f)
-        self.assertEqual(self.server.handler.last_received_data, RETR_DATA)
+        self.assertEqual(self.server.handler_instance.last_received_data, RETR_DATA)
         # test new callback arg
         flag = []
         f.seek(0)
@@ -551,14 +559,14 @@ class TestFTPClass(TestCase):
     def test_makeport(self):
         self.client.makeport()
         # IPv4 is in use, just make sure send_eprt has not been used
-        self.assertEqual(self.server.handler.last_received_cmd, 'port')
+        self.assertEqual(self.server.handler_instance.last_received_cmd, 'port')
 
     def test_makepasv(self):
         host, port = self.client.makepasv()
         conn = socket.create_connection((host, port), 10)
         conn.close()
         # IPv4 is in use, just make sure send_epsv has not been used
-        self.assertEqual(self.server.handler.last_received_cmd, 'pasv')
+        self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
 
     def test_line_too_long(self):
         self.assertRaises(ftplib.Error, self.client.sendcmd,
@@ -600,13 +608,13 @@ class TestIPv6Environment(TestCase):
 
     def test_makeport(self):
         self.client.makeport()
-        self.assertEqual(self.server.handler.last_received_cmd, 'eprt')
+        self.assertEqual(self.server.handler_instance.last_received_cmd, 'eprt')
 
     def test_makepasv(self):
         host, port = self.client.makepasv()
         conn = socket.create_connection((host, port), 10)
         conn.close()
-        self.assertEqual(self.server.handler.last_received_cmd, 'epsv')
+        self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
 
     def test_transfer(self):
         def retr():
@@ -642,7 +650,7 @@ class TestTLS_FTPClass(TestCase):
     def setUp(self):
         self.server = DummyTLS_FTPServer((HOST, 0))
         self.server.start()
-        self.client = ftplib.FTP_TLS(timeout=10)
+        self.client = ftplib.FTP_TLS(timeout=TIMEOUT)
         self.client.connect(self.server.host, self.server.port)
 
     def tearDown(self):
@@ -695,6 +703,59 @@ class TestTLS_FTPClass(TestCase):
         finally:
             self.client.ssl_version = ssl.PROTOCOL_TLSv1
 
+    def test_context(self):
+        self.client.quit()
+        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+        self.assertRaises(ValueError, ftplib.FTP_TLS, keyfile=CERTFILE,
+                          context=ctx)
+        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
+                          context=ctx)
+        self.assertRaises(ValueError, ftplib.FTP_TLS, certfile=CERTFILE,
+                          keyfile=CERTFILE, context=ctx)
+
+        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
+        self.client.connect(self.server.host, self.server.port)
+        self.assertNotIsInstance(self.client.sock, ssl.SSLSocket)
+        self.client.auth()
+        self.assertIs(self.client.sock.context, ctx)
+        self.assertIsInstance(self.client.sock, ssl.SSLSocket)
+
+        self.client.prot_p()
+        sock = self.client.transfercmd('list')
+        try:
+            self.assertIs(sock.context, ctx)
+            self.assertIsInstance(sock, ssl.SSLSocket)
+        finally:
+            sock.close()
+
+    def test_check_hostname(self):
+        self.client.quit()
+        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+        ctx.verify_mode = ssl.CERT_REQUIRED
+        ctx.check_hostname = True
+        ctx.load_verify_locations(CAFILE)
+        self.client = ftplib.FTP_TLS(context=ctx, timeout=TIMEOUT)
+
+        # 127.0.0.1 doesn't match SAN
+        self.client.connect(self.server.host, self.server.port)
+        with self.assertRaises(ssl.CertificateError):
+            self.client.auth()
+        # exception quits connection
+
+        self.client.connect(self.server.host, self.server.port)
+        self.client.prot_p()
+        with self.assertRaises(ssl.CertificateError):
+            self.client.transfercmd("list").close()
+        self.client.quit()
+
+        self.client.connect("localhost", self.server.port)
+        self.client.auth()
+        self.client.quit()
+
+        self.client.connect("localhost", self.server.port)
+        self.client.prot_p()
+        self.client.transfercmd("list").close()
+
 
 class TestTimeouts(TestCase):
 
index 445ad9e..7b3cb96 100644 (file)
@@ -89,9 +89,11 @@ class TestPartial(unittest.TestCase):
         # exercise special code paths for no keyword args in
         # either the partial object or the caller
         p = self.thetype(capture)
+        self.assertEqual(p.keywords, {})
         self.assertEqual(p(), ((), {}))
         self.assertEqual(p(a=1), ((), {'a':1}))
         p = self.thetype(capture, a=1)
+        self.assertEqual(p.keywords, {'a':1})
         self.assertEqual(p(), ((), {'a':1}))
         self.assertEqual(p(b=2), ((), {'a':1, 'b':2}))
         # keyword args in the call override those in the partial object
@@ -146,8 +148,9 @@ class TestPartial(unittest.TestCase):
     def test_pickle(self):
         f = self.thetype(signature, 'asdf', bar=True)
         f.add_something_to__dict__ = True
-        f_copy = pickle.loads(pickle.dumps(f))
-        self.assertEqual(signature(f), signature(f_copy))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            f_copy = pickle.loads(pickle.dumps(f, proto))
+            self.assertEqual(signature(f), signature(f_copy))
 
     # Issue 6083: Reference counting bug
     def test_setstate_refcount(self):
index fd874c3..ed01c98 100644 (file)
@@ -1,5 +1,5 @@
 import unittest
-from test.test_support import verbose, run_unittest
+from test.test_support import verbose, run_unittest, start_threads
 import sys
 import time
 import gc
@@ -352,17 +352,13 @@ class GCTests(unittest.TestCase):
         old_checkinterval = sys.getcheckinterval()
         sys.setcheckinterval(3)
         try:
-            exit = False
+            exit = []
             threads = []
             for i in range(N_THREADS):
                 t = threading.Thread(target=run_thread)
                 threads.append(t)
-            for t in threads:
-                t.start()
-            time.sleep(1.0)
-            exit = True
-            for t in threads:
-                t.join()
+            with start_threads(threads, lambda: exit.append(1)):
+                time.sleep(1.0)
         finally:
             sys.setcheckinterval(old_checkinterval)
         gc.collect()
index c2f90b2..9656010 100644 (file)
@@ -72,7 +72,7 @@ def python_is_optimized():
     for opt in cflags.split():
         if opt.startswith('-O'):
             final_opt = opt
-    return (final_opt and final_opt != '-O0')
+    return final_opt not in ('', '-O0', '-Og')
 
 def gdb_has_frame_select():
     # Does this build of gdb have gdb.Frame.select ?
@@ -118,7 +118,28 @@ class DebuggerTests(unittest.TestCase):
         # Generate a list of commands in gdb's language:
         commands = ['set breakpoint pending yes',
                     'break %s' % breakpoint,
+
+                    # The tests assume that the first frame of printed
+                    #  backtrace will not contain program counter,
+                    #  that is however not guaranteed by gdb
+                    #  therefore we need to use 'set print address off' to
+                    #  make sure the counter is not there. For example:
+                    # #0 in PyObject_Print ...
+                    #  is assumed, but sometimes this can be e.g.
+                    # #0 0x00003fffb7dd1798 in PyObject_Print ...
+                    'set print address off',
+
                     'run']
+
+        # GDB as of 7.4 onwards can distinguish between the
+        # value of a variable at entry vs current value:
+        #   http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
+        # which leads to the selftests failing with errors like this:
+        #   AssertionError: 'v@entry=()' != '()'
+        # Disable this:
+        if (gdb_major_version, gdb_minor_version) >= (7, 4):
+            commands += ['set print entry-values no']
+
         if cmds_after_breakpoint:
             commands += cmds_after_breakpoint
         else:
@@ -164,6 +185,8 @@ class DebuggerTests(unittest.TestCase):
             'linux-vdso.so',
             'warning: Could not load shared library symbols for '
             'linux-gate.so',
+            'warning: Could not load shared library symbols for '
+            'linux-vdso64.so',
             'Do you need "set solib-search-path" or '
             '"set sysroot"?',
             'warning: Source file is more recent than executable.',
index 94380b1..741b755 100644 (file)
@@ -243,11 +243,13 @@ class CommonTest(GenericTest):
     def test_realpath(self):
         self.assertIn("foo", self.pathmodule.realpath("foo"))
 
+    @test_support.requires_unicode
     def test_normpath_issue5827(self):
         # Make sure normpath preserves unicode
         for path in (u'', u'.', u'/', u'\\', u'///foo/.//bar//'):
             self.assertIsInstance(self.pathmodule.normpath(path), unicode)
 
+    @test_support.requires_unicode
     def test_abspath_issue3426(self):
         # Check that abspath returns unicode when the arg is unicode
         # with both ASCII and non-ASCII cwds.
index f036954..3f792bb 100644 (file)
@@ -80,6 +80,12 @@ class GettextBaseTest(unittest.TestCase):
         del self.env
         shutil.rmtree(os.path.split(LOCALEDIR)[0])
 
+GNU_MO_DATA_ISSUE_17898 = b'''\
+3hIElQAAAAABAAAAHAAAACQAAAAAAAAAAAAAAAAAAAAsAAAAggAAAC0AAAAAUGx1cmFsLUZvcm1z
+OiBucGx1cmFscz0yOyBwbHVyYWw9KG4gIT0gMSk7CiMtIy0jLSMtIyAgbWVzc2FnZXMucG8gKEVk
+WCBTdHVkaW8pICAjLSMtIy0jLSMKQ29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PVVU
+Ri04CgA=
+'''
 
 class GettextTestCase1(GettextBaseTest):
     def setUp(self):
@@ -291,6 +297,14 @@ class PluralFormsTestCase(GettextBaseTest):
         # Test for a dangerous expression
         raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)")
 
+class GNUTranslationParsingTest(GettextBaseTest):
+    def test_plural_form_error_issue17898(self):
+        with open(MOFILE, 'wb') as fp:
+            fp.write(base64.decodestring(GNU_MO_DATA_ISSUE_17898))
+        with open(MOFILE, 'rb') as fp:
+            # If this runs cleanly, the bug is fixed.
+            t = gettext.GNUTranslations(fp)
+
 
 class UnicodeTranslationsTest(GettextBaseTest):
     def setUp(self):
@@ -465,3 +479,16 @@ msgstr ""
 "Content-Transfer-Encoding: quoted-printable\n"
 "Generated-By: pygettext.py 1.3\n"
 '''
+
+#
+# messages.po, used for bug 17898
+#
+
+'''
+# test file for http://bugs.python.org/issue17898
+msgid ""
+msgstr ""
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"#-#-#-#-#  messages.po (EdX Studio)  #-#-#-#-#\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+'''
index 7f24981..5025b91 100644 (file)
@@ -30,6 +30,14 @@ class TestGzip(unittest.TestCase):
     def tearDown(self):
         test_support.unlink(self.filename)
 
+    def write_and_read_back(self, data, mode='b'):
+        b_data = memoryview(data).tobytes()
+        with gzip.GzipFile(self.filename, 'w'+mode) as f:
+            l = f.write(data)
+        self.assertEqual(l, len(b_data))
+        with gzip.GzipFile(self.filename, 'r'+mode) as f:
+            self.assertEqual(f.read(), b_data)
+
     @test_support.requires_unicode
     def test_unicode_filename(self):
         unicode_filename = test_support.TESTFN_UNICODE
@@ -37,6 +45,7 @@ class TestGzip(unittest.TestCase):
             unicode_filename.encode(test_support.TESTFN_ENCODING)
         except (UnicodeError, TypeError):
             self.skipTest("Requires unicode filenames support")
+        self.filename = unicode_filename
         with gzip.GzipFile(unicode_filename, "wb") as f:
             f.write(data1 * 50)
         with gzip.GzipFile(unicode_filename, "rb") as f:
@@ -60,6 +69,25 @@ class TestGzip(unittest.TestCase):
         # Test multiple close() calls.
         f.close()
 
+    # The following test_write_xy methods test that write accepts
+    # the corresponding bytes-like object type as input
+    # and that the data written equals bytes(xy) in all cases.
+    def test_write_memoryview(self):
+        self.write_and_read_back(memoryview(data1 * 50))
+
+    def test_write_incompatible_type(self):
+        # Test that non-bytes-like types raise TypeError.
+        # Issue #21560: attempts to write incompatible types
+        # should not affect the state of the fileobject
+        with gzip.GzipFile(self.filename, 'wb') as f:
+            with self.assertRaises(UnicodeEncodeError):
+                f.write(u'\xff')
+            with self.assertRaises(TypeError):
+                f.write([1])
+            f.write(data1)
+        with gzip.GzipFile(self.filename, 'rb') as f:
+            self.assertEqual(f.read(), data1)
+
     def test_read(self):
         self.test_write()
         # Try reading.
index d3e6fce..fc7c571 100644 (file)
@@ -1,4 +1,5 @@
 import httplib
+import itertools
 import array
 import StringIO
 import socket
@@ -25,6 +26,7 @@ class FakeSocket:
         self.text = text
         self.fileclass = fileclass
         self.data = ''
+        self.file_closed = False
         self.host = host
         self.port = port
 
@@ -34,7 +36,13 @@ class FakeSocket:
     def makefile(self, mode, bufsize=None):
         if mode != 'r' and mode != 'rb':
             raise httplib.UnimplementedFileMode()
-        return self.fileclass(self.text)
+        # keep the file around so we can check how much was read from it
+        self.file = self.fileclass(self.text)
+        self.file.close = self.file_close #nerf close ()
+        return self.file
+
+    def file_close(self):
+        self.file_closed = True
 
     def close(self):
         pass
@@ -115,21 +123,59 @@ class HeaderTests(TestCase):
                     self.content_length = kv[1].strip()
                 list.append(self, item)
 
-        # POST with empty body
-        conn = httplib.HTTPConnection('example.com')
-        conn.sock = FakeSocket(None)
-        conn._buffer = ContentLengthChecker()
-        conn.request('POST', '/', '')
-        self.assertEqual(conn._buffer.content_length, '0',
-                        'Header Content-Length not set')
-
-        # PUT request with empty body
-        conn = httplib.HTTPConnection('example.com')
-        conn.sock = FakeSocket(None)
-        conn._buffer = ContentLengthChecker()
-        conn.request('PUT', '/', '')
-        self.assertEqual(conn._buffer.content_length, '0',
-                        'Header Content-Length not set')
+        # Here, we're testing that methods expecting a body get a
+        # content-length set to zero if the body is empty (either None or '')
+        bodies = (None, '')
+        methods_with_body = ('PUT', 'POST', 'PATCH')
+        for method, body in itertools.product(methods_with_body, bodies):
+            conn = httplib.HTTPConnection('example.com')
+            conn.sock = FakeSocket(None)
+            conn._buffer = ContentLengthChecker()
+            conn.request(method, '/', body)
+            self.assertEqual(
+                conn._buffer.content_length, '0',
+                'Header Content-Length incorrect on {}'.format(method)
+            )
+
+        # For these methods, we make sure that content-length is not set when
+        # the body is None because it might cause unexpected behaviour on the
+        # server.
+        methods_without_body = (
+             'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
+        )
+        for method in methods_without_body:
+            conn = httplib.HTTPConnection('example.com')
+            conn.sock = FakeSocket(None)
+            conn._buffer = ContentLengthChecker()
+            conn.request(method, '/', None)
+            self.assertEqual(
+                conn._buffer.content_length, None,
+                'Header Content-Length set for empty body on {}'.format(method)
+            )
+
+        # If the body is set to '', that's considered to be "present but
+        # empty" rather than "missing", so content length would be set, even
+        # for methods that don't expect a body.
+        for method in methods_without_body:
+            conn = httplib.HTTPConnection('example.com')
+            conn.sock = FakeSocket(None)
+            conn._buffer = ContentLengthChecker()
+            conn.request(method, '/', '')
+            self.assertEqual(
+                conn._buffer.content_length, '0',
+                'Header Content-Length incorrect on {}'.format(method)
+            )
+
+        # If the body is set, make sure Content-Length is set.
+        for method in itertools.chain(methods_without_body, methods_with_body):
+            conn = httplib.HTTPConnection('example.com')
+            conn.sock = FakeSocket(None)
+            conn._buffer = ContentLengthChecker()
+            conn.request(method, '/', ' ')
+            self.assertEqual(
+                conn._buffer.content_length, '1',
+                'Header Content-Length incorrect on {}'.format(method)
+            )
 
     def test_putheader(self):
         conn = httplib.HTTPConnection('example.com')
@@ -138,6 +184,33 @@ class HeaderTests(TestCase):
         conn.putheader('Content-length',42)
         self.assertIn('Content-length: 42', conn._buffer)
 
+        conn.putheader('Foo', ' bar ')
+        self.assertIn(b'Foo:  bar ', conn._buffer)
+        conn.putheader('Bar', '\tbaz\t')
+        self.assertIn(b'Bar: \tbaz\t', conn._buffer)
+        conn.putheader('Authorization', 'Bearer mytoken')
+        self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
+        conn.putheader('IterHeader', 'IterA', 'IterB')
+        self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
+        conn.putheader('LatinHeader', b'\xFF')
+        self.assertIn(b'LatinHeader: \xFF', conn._buffer)
+        conn.putheader('Utf8Header', b'\xc3\x80')
+        self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
+        conn.putheader('C1-Control', b'next\x85line')
+        self.assertIn(b'C1-Control: next\x85line', conn._buffer)
+        conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
+        self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
+        conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
+        self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
+        conn.putheader('Key Space', 'value')
+        self.assertIn(b'Key Space: value', conn._buffer)
+        conn.putheader('KeySpace ', 'value')
+        self.assertIn(b'KeySpace : value', conn._buffer)
+        conn.putheader(b'Nonbreak\xa0Space', 'value')
+        self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
+        conn.putheader(b'\xa0NonbreakSpace', 'value')
+        self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
+
     def test_ipv6host_header(self):
         # Default host header on IPv6 transaction should wrapped by [] if
         # its actual IPv6 address
@@ -157,6 +230,45 @@ class HeaderTests(TestCase):
         conn.request('GET', '/foo')
         self.assertTrue(sock.data.startswith(expected))
 
+    def test_malformed_headers_coped_with(self):
+        # Issue 19996
+        body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
+        sock = FakeSocket(body)
+        resp = httplib.HTTPResponse(sock)
+        resp.begin()
+
+        self.assertEqual(resp.getheader('First'), 'val')
+        self.assertEqual(resp.getheader('Second'), 'val')
+
+    def test_invalid_headers(self):
+        conn = httplib.HTTPConnection('example.com')
+        conn.sock = FakeSocket('')
+        conn.putrequest('GET', '/')
+
+        # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
+        # longer allowed in header names
+        cases = (
+            (b'Invalid\r\nName', b'ValidValue'),
+            (b'Invalid\rName', b'ValidValue'),
+            (b'Invalid\nName', b'ValidValue'),
+            (b'\r\nInvalidName', b'ValidValue'),
+            (b'\rInvalidName', b'ValidValue'),
+            (b'\nInvalidName', b'ValidValue'),
+            (b' InvalidName', b'ValidValue'),
+            (b'\tInvalidName', b'ValidValue'),
+            (b'Invalid:Name', b'ValidValue'),
+            (b':InvalidName', b'ValidValue'),
+            (b'ValidName', b'Invalid\r\nValue'),
+            (b'ValidName', b'Invalid\rValue'),
+            (b'ValidName', b'Invalid\nValue'),
+            (b'ValidName', b'InvalidValue\r\n'),
+            (b'ValidName', b'InvalidValue\r'),
+            (b'ValidName', b'InvalidValue\n'),
+        )
+        for name, value in cases:
+            with self.assertRaisesRegexp(ValueError, 'Invalid header'):
+                conn.putheader(name, value)
+
 
 class BasicTest(TestCase):
     def test_status_lines(self):
@@ -433,12 +545,32 @@ class BasicTest(TestCase):
         self.assertEqual(resp.read(), '')
         self.assertTrue(resp.isclosed())
 
+    def test_error_leak(self):
+        # Test that the socket is not leaked if getresponse() fails
+        conn = httplib.HTTPConnection('example.com')
+        response = []
+        class Response(httplib.HTTPResponse):
+            def __init__(self, *pos, **kw):
+                response.append(self)  # Avoid garbage collector closing the socket
+                httplib.HTTPResponse.__init__(self, *pos, **kw)
+        conn.response_class = Response
+        conn.sock = FakeSocket('')  # Emulate server dropping connection
+        conn.request('GET', '/')
+        self.assertRaises(httplib.BadStatusLine, conn.getresponse)
+        self.assertTrue(response)
+        #self.assertTrue(response[0].closed)
+        self.assertTrue(conn.sock.file_closed)
+
 class OfflineTest(TestCase):
     def test_responses(self):
         self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
 
 
-class SourceAddressTest(TestCase):
+class TestServerMixin:
+    """A limited socket server mixin.
+
+    This is used by test cases for testing http connection end points.
+    """
     def setUp(self):
         self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.port = test_support.bind_port(self.serv)
@@ -453,6 +585,7 @@ class SourceAddressTest(TestCase):
         self.serv.close()
         self.serv = None
 
+class SourceAddressTest(TestServerMixin, TestCase):
     def testHTTPConnectionSourceAddress(self):
         self.conn = httplib.HTTPConnection(HOST, self.port,
                 source_address=('', self.source_port))
@@ -469,6 +602,24 @@ class SourceAddressTest(TestCase):
         # for an ssl_wrapped connect() to actually return from.
 
 
+class HTTPTest(TestServerMixin, TestCase):
+    def testHTTPConnection(self):
+        self.conn = httplib.HTTP(host=HOST, port=self.port, strict=None)
+        self.conn.connect()
+        self.assertEqual(self.conn._conn.host, HOST)
+        self.assertEqual(self.conn._conn.port, self.port)
+
+    def testHTTPWithConnectHostPort(self):
+        testhost = 'unreachable.test.domain'
+        testport = '80'
+        self.conn = httplib.HTTP(host=testhost, port=testport)
+        self.conn.connect(host=HOST, port=self.port)
+        self.assertNotEqual(self.conn._conn.host, testhost)
+        self.assertNotEqual(self.conn._conn.port, testport)
+        self.assertEqual(self.conn._conn.host, HOST)
+        self.assertEqual(self.conn._conn.port, self.port)
+
+
 class TimeoutTest(TestCase):
     PORT = None
 
@@ -514,6 +665,7 @@ class TimeoutTest(TestCase):
         self.assertEqual(httpConn.sock.gettimeout(), 30)
         httpConn.close()
 
+
 class HTTPSTest(TestCase):
 
     def setUp(self):
@@ -690,7 +842,8 @@ class TunnelTests(TestCase):
 @test_support.reap_threads
 def test_main(verbose=None):
     test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
-                              HTTPSTest, SourceAddressTest, TunnelTests)
+                              HTTPTest, HTTPSTest, SourceAddressTest,
+                              TunnelTests)
 
 if __name__ == '__main__':
     test_main()
index bd26140..706dfc7 100644 (file)
@@ -321,6 +321,12 @@ class SimpleHTTPServerTestCase(BaseTestCase):
         self.check_status_and_reason(response, 200)
         response = self.request(self.tempdir_name)
         self.check_status_and_reason(response, 301)
+        response = self.request(self.tempdir_name + '/?hi=2')
+        self.check_status_and_reason(response, 200)
+        response = self.request(self.tempdir_name + '?hi=1')
+        self.check_status_and_reason(response, 301)
+        self.assertEqual(response.getheader("Location"),
+                         self.tempdir_name + "/?hi=1")
         response = self.request('/ThisDoesNotExist')
         self.check_status_and_reason(response, 404)
         response = self.request('/' + 'ThisDoesNotExist' + '/')
index 2a3b4a3..bbc804b 100644 (file)
@@ -564,13 +564,44 @@ class IOTest(unittest.TestCase):
         with self.open(zero, "r") as f:
             self.assertRaises(OverflowError, f.read)
 
-    def test_flush_error_on_close(self):
-        f = self.open(support.TESTFN, "wb", buffering=0)
+    def check_flush_error_on_close(self, *args, **kwargs):
+        # Test that the file is closed despite failed flush
+        # and that flush() is called before file closed.
+        f = self.open(*args, **kwargs)
+        closed = []
         def bad_flush():
+            closed[:] = [f.closed]
             raise IOError()
         f.flush = bad_flush
         self.assertRaises(IOError, f.close) # exception not swallowed
         self.assertTrue(f.closed)
+        self.assertTrue(closed)      # flush() called
+        self.assertFalse(closed[0])  # flush() called before file closed
+        f.flush = lambda: None  # break reference loop
+
+    def test_flush_error_on_close(self):
+        # raw file
+        # Issue #5700: io.FileIO calls flush() after file closed
+        self.check_flush_error_on_close(support.TESTFN, 'wb', buffering=0)
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'wb', buffering=0)
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False)
+        os.close(fd)
+        # buffered io
+        self.check_flush_error_on_close(support.TESTFN, 'wb')
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'wb')
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'wb', closefd=False)
+        os.close(fd)
+        # text io
+        self.check_flush_error_on_close(support.TESTFN, 'w')
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'w')
+        fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT)
+        self.check_flush_error_on_close(fd, 'w', closefd=False)
+        os.close(fd)
 
     def test_multi_close(self):
         f = self.open(support.TESTFN, "wb", buffering=0)
@@ -654,6 +685,8 @@ class CommonBufferedTests:
         self.assertIs(buf.detach(), raw)
         self.assertRaises(ValueError, buf.detach)
 
+        repr(buf)  # Should still work
+
     def test_fileno(self):
         rawio = self.MockRawIO()
         bufio = self.tp(rawio)
@@ -739,13 +772,22 @@ class CommonBufferedTests:
         self.assertEqual(repr(b), "<%s name='dummy'>" % clsname)
 
     def test_flush_error_on_close(self):
+        # Test that buffered file is closed despite failed flush
+        # and that flush() is called before file closed.
         raw = self.MockRawIO()
+        closed = []
         def bad_flush():
+            closed[:] = [b.closed, raw.closed]
             raise IOError()
         raw.flush = bad_flush
         b = self.tp(raw)
         self.assertRaises(IOError, b.close) # exception not swallowed
         self.assertTrue(b.closed)
+        self.assertTrue(raw.closed)
+        self.assertTrue(closed)      # flush() called
+        self.assertFalse(closed[0])  # flush() called before file closed
+        self.assertFalse(closed[1])
+        raw.flush = lambda: None  # break reference loop
 
     def test_close_error_on_close(self):
         raw = self.MockRawIO()
@@ -943,11 +985,8 @@ class BufferedReaderTest(unittest.TestCase, CommonBufferedTests):
                         errors.append(e)
                         raise
                 threads = [threading.Thread(target=f) for x in range(20)]
-                for t in threads:
-                    t.start()
-                time.sleep(0.02) # yield
-                for t in threads:
-                    t.join()
+                with support.start_threads(threads):
+                    time.sleep(0.02) # yield
                 self.assertFalse(errors,
                     "the following exceptions were caught: %r" % errors)
                 s = b''.join(results)
@@ -1257,11 +1296,8 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests):
                         errors.append(e)
                         raise
                 threads = [threading.Thread(target=f) for x in range(20)]
-                for t in threads:
-                    t.start()
-                time.sleep(0.02) # yield
-                for t in threads:
-                    t.join()
+                with support.start_threads(threads):
+                    time.sleep(0.02) # yield
                 self.assertFalse(errors,
                     "the following exceptions were caught: %r" % errors)
                 bufio.close()
@@ -1453,6 +1489,51 @@ class BufferedRWPairTest(unittest.TestCase):
         pair.close()
         self.assertTrue(pair.closed)
 
+    def test_reader_close_error_on_close(self):
+        def reader_close():
+            reader_non_existing
+        reader = self.MockRawIO()
+        reader.close = reader_close
+        writer = self.MockRawIO()
+        pair = self.tp(reader, writer)
+        with self.assertRaises(NameError) as err:
+            pair.close()
+        self.assertIn('reader_non_existing', str(err.exception))
+        self.assertTrue(pair.closed)
+        self.assertFalse(reader.closed)
+        self.assertTrue(writer.closed)
+
+    def test_writer_close_error_on_close(self):
+        def writer_close():
+            writer_non_existing
+        reader = self.MockRawIO()
+        writer = self.MockRawIO()
+        writer.close = writer_close
+        pair = self.tp(reader, writer)
+        with self.assertRaises(NameError) as err:
+            pair.close()
+        self.assertIn('writer_non_existing', str(err.exception))
+        self.assertFalse(pair.closed)
+        self.assertTrue(reader.closed)
+        self.assertFalse(writer.closed)
+
+    def test_reader_writer_close_error_on_close(self):
+        def reader_close():
+            reader_non_existing
+        def writer_close():
+            writer_non_existing
+        reader = self.MockRawIO()
+        reader.close = reader_close
+        writer = self.MockRawIO()
+        writer.close = writer_close
+        pair = self.tp(reader, writer)
+        with self.assertRaises(NameError) as err:
+            pair.close()
+        self.assertIn('reader_non_existing', str(err.exception))
+        self.assertFalse(pair.closed)
+        self.assertFalse(reader.closed)
+        self.assertFalse(writer.closed)
+
     def test_isatty(self):
         class SelectableIsAtty(MockRawIO):
             def __init__(self, isatty):
@@ -1909,6 +1990,17 @@ class TextIOWrapperTest(unittest.TestCase):
         self.assertRaises(TypeError, t.__init__, b, newline=42)
         self.assertRaises(ValueError, t.__init__, b, newline='xyzzy')
 
+    def test_uninitialized(self):
+        t = self.TextIOWrapper.__new__(self.TextIOWrapper)
+        del t
+        t = self.TextIOWrapper.__new__(self.TextIOWrapper)
+        self.assertRaises(Exception, repr, t)
+        self.assertRaisesRegexp((ValueError, AttributeError),
+                                'uninitialized|has no attribute',
+                                t.read, 0)
+        t.__init__(self.MockRawIO())
+        self.assertEqual(t.read(0), u'')
+
     def test_detach(self):
         r = self.BytesIO()
         b = self.BufferedWriter(r)
@@ -1922,6 +2014,12 @@ class TextIOWrapperTest(unittest.TestCase):
         self.assertEqual(r.getvalue(), b"howdy")
         self.assertRaises(ValueError, t.detach)
 
+        # Operations independent of the detached stream should still work
+        repr(t)
+        self.assertEqual(t.encoding, "ascii")
+        self.assertEqual(t.errors, "strict")
+        self.assertFalse(t.line_buffering)
+
     def test_repr(self):
         raw = self.BytesIO("hello".encode("utf-8"))
         b = self.BufferedReader(raw)
@@ -1936,6 +2034,9 @@ class TextIOWrapperTest(unittest.TestCase):
         self.assertEqual(repr(t),
                          "<%s.TextIOWrapper name='dummy' encoding='utf-8'>" % modname)
 
+        t.buffer.detach()
+        repr(t)  # Should not raise an exception
+
     def test_line_buffering(self):
         r = self.BytesIO()
         b = self.BufferedWriter(r, 1000)
@@ -2459,26 +2560,31 @@ class TextIOWrapperTest(unittest.TestCase):
                 text = "Thread%03d\n" % n
                 event.wait()
                 f.write(text)
-            threads = [threading.Thread(target=lambda n=x: run(n))
+            threads = [threading.Thread(target=run, args=(x,))
                        for x in range(20)]
-            for t in threads:
-                t.start()
-            time.sleep(0.02)
-            event.set()
-            for t in threads:
-                t.join()
+            with support.start_threads(threads, event.set):
+                time.sleep(0.02)
         with self.open(support.TESTFN) as f:
             content = f.read()
             for n in range(20):
                 self.assertEqual(content.count("Thread%03d\n" % n), 1)
 
     def test_flush_error_on_close(self):
+        # Test that text file is closed despite failed flush
+        # and that flush() is called before file closed.
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
+        closed = []
         def bad_flush():
+            closed[:] = [txt.closed, txt.buffer.closed]
             raise IOError()
         txt.flush = bad_flush
         self.assertRaises(IOError, txt.close) # exception not swallowed
         self.assertTrue(txt.closed)
+        self.assertTrue(txt.buffer.closed)
+        self.assertTrue(closed)      # flush() called
+        self.assertFalse(closed[0])  # flush() called before file closed
+        self.assertFalse(closed[1])
+        txt.flush = lambda: None  # break reference loop
 
     def test_multi_close(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2537,6 +2643,9 @@ class CTextIOWrapperTest(TextIOWrapperTest):
         self.assertRaises(ValueError, t.__init__, b, newline='xyzzy')
         self.assertRaises(ValueError, t.read)
 
+        t = self.TextIOWrapper.__new__(self.TextIOWrapper)
+        self.assertRaises(Exception, repr, t)
+
     def test_garbage_collection(self):
         # C TextIOWrapper objects are collected, and collecting them flushes
         # all data to disk.
@@ -2934,9 +3043,11 @@ class SignalsTest(unittest.TestCase):
             # return with a successful (partial) result rather than an EINTR.
             # The buffered IO layer must check for pending signal
             # handlers, which in this case will invoke alarm_interrupt().
-            self.assertRaises(ZeroDivisionError,
-                        wio.write, item * (support.PIPE_MAX_SIZE // len(item) + 1))
-            t.join()
+            try:
+                with self.assertRaises(ZeroDivisionError):
+                    wio.write(item * (support.PIPE_MAX_SIZE // len(item) + 1))
+            finally:
+                t.join()
             # We got one byte, get another one and check that it isn't a
             # repeat of the first one.
             read_results.append(os.read(r, 1))
@@ -3041,11 +3152,15 @@ class SignalsTest(unittest.TestCase):
         # received (forcing a first EINTR in write()).
         read_results = []
         write_finished = False
+        error = [None]
         def _read():
-            while not write_finished:
-                while r in select.select([r], [], [], 1.0)[0]:
-                    s = os.read(r, 1024)
-                    read_results.append(s)
+            try:
+                while not write_finished:
+                    while r in select.select([r], [], [], 1.0)[0]:
+                        s = os.read(r, 1024)
+                        read_results.append(s)
+            except BaseException as exc:
+                error[0] = exc
         t = threading.Thread(target=_read)
         t.daemon = True
         def alarm1(sig, frame):
@@ -3066,6 +3181,8 @@ class SignalsTest(unittest.TestCase):
             wio.flush()
             write_finished = True
             t.join()
+
+            self.assertIsNone(error[0])
             self.assertEqual(N, sum(len(x) for x in read_results))
         finally:
             write_finished = True
index 5da4a6f..753aa17 100644 (file)
@@ -137,6 +137,11 @@ class TestBasicOps(unittest.TestCase):
                 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
                 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
 
+    @test_support.bigaddrspacetest
+    def test_combinations_overflow(self):
+        with self.assertRaises((OverflowError, MemoryError)):
+            combinations("AA", 2**29)
+
     @test_support.impl_detail("tuple reuse is specific to CPython")
     def test_combinations_tuple_reuse(self):
         self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
@@ -208,6 +213,11 @@ class TestBasicOps(unittest.TestCase):
                 self.assertEqual(result, list(cwr1(values, r)))         # matches first pure python version
                 self.assertEqual(result, list(cwr2(values, r)))         # matches second pure python version
 
+    @test_support.bigaddrspacetest
+    def test_combinations_with_replacement_overflow(self):
+        with self.assertRaises((OverflowError, MemoryError)):
+            combinations_with_replacement("AA", 2**30)
+
     @test_support.impl_detail("tuple reuse is specific to CPython")
     def test_combinations_with_replacement_tuple_reuse(self):
         cwr = combinations_with_replacement
@@ -274,6 +284,11 @@ class TestBasicOps(unittest.TestCase):
                     self.assertEqual(result, list(permutations(values, None))) # test r as None
                     self.assertEqual(result, list(permutations(values)))       # test default r
 
+    @test_support.bigaddrspacetest
+    def test_permutations_overflow(self):
+        with self.assertRaises((OverflowError, MemoryError)):
+            permutations("A", 2**30)
+
     @test_support.impl_detail("tuple reuse is specific to CPython")
     def test_permutations_tuple_reuse(self):
         self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
@@ -358,7 +373,8 @@ class TestBasicOps(unittest.TestCase):
             c = count(value)
             self.assertEqual(next(copy.copy(c)), value)
             self.assertEqual(next(copy.deepcopy(c)), value)
-            self.assertEqual(next(pickle.loads(pickle.dumps(c))), value)
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                self.assertEqual(next(pickle.loads(pickle.dumps(c, proto))), value)
 
     def test_count_with_stride(self):
         self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
@@ -691,6 +707,11 @@ class TestBasicOps(unittest.TestCase):
             args = map(iter, args)
             self.assertEqual(len(list(product(*args))), expected_len)
 
+    @test_support.bigaddrspacetest
+    def test_product_overflow(self):
+        with self.assertRaises((OverflowError, MemoryError)):
+            product(*(['ab']*2**5), repeat=2**25)
+
     @test_support.impl_detail("tuple reuse is specific to CPython")
     def test_product_tuple_reuse(self):
         self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
@@ -928,8 +949,12 @@ class TestBasicOps(unittest.TestCase):
     # Issue 13454: Crash when deleting backward iterator from tee()
     def test_tee_del_backward(self):
         forward, backward = tee(repeat(None, 20000000))
-        any(forward)  # exhaust the iterator
-        del backward
+        try:
+            any(forward)  # exhaust the iterator
+            del backward
+        except:
+            del forward, backward
+            raise
 
     def test_StopIteration(self):
         self.assertRaises(StopIteration, izip().next)
index b5f80a4..6f7ecd1 100644 (file)
@@ -124,6 +124,22 @@ class LineCacheTests(unittest.TestCase):
                 self.assertEqual(line, getline(source_name, index + 1))
                 source_list.append(line)
 
+    def test_memoryerror(self):
+        lines = linecache.getlines(FILENAME)
+        self.assertTrue(lines)
+        def raise_memoryerror(*args, **kwargs):
+            raise MemoryError
+        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
+            lines2 = linecache.getlines(FILENAME)
+        self.assertEqual(lines2, lines)
+
+        linecache.clearcache()
+        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
+            lines3 = linecache.getlines(FILENAME)
+        self.assertEqual(lines3, [])
+        self.assertEqual(linecache.getlines(FILENAME), lines)
+
+
 def test_main():
     support.run_unittest(LineCacheTests)
 
index 96ad61f..be936de 100644 (file)
@@ -59,6 +59,7 @@ class MacPathTestCase(unittest.TestCase):
         self.assertEqual(splitext(""), ('', ''))
         self.assertEqual(splitext("foo.bar.ext"), ('foo.bar', '.ext'))
 
+    @test_support.requires_unicode
     def test_normpath(self):
         # Issue 5827: Make sure normpath preserves unicode
         for path in (u'', u'.', u'/', u'\\', u':', u'///foo/.//bar//'):
index 59fa3eb..1967c48 100644 (file)
@@ -6,6 +6,11 @@ import sys
 import unittest
 import os
 
+try:
+    import _testcapi
+except ImportError:
+    _testcapi = None
+
 class IntTestCase(unittest.TestCase):
     def test_ints(self):
         # Test the full range of Python ints.
@@ -316,6 +321,65 @@ class LargeValuesTestCase(unittest.TestCase):
         self.check_unmarshallable(bytearray(size))
 
 
+@test_support.cpython_only
+@unittest.skipUnless(_testcapi, 'requires _testcapi')
+class CAPI_TestCase(unittest.TestCase):
+
+    def test_write_long_to_file(self):
+        for v in range(marshal.version + 1):
+            _testcapi.pymarshal_write_long_to_file(0x12345678, test_support.TESTFN, v)
+            with open(test_support.TESTFN, 'rb') as f:
+                data = f.read()
+            test_support.unlink(test_support.TESTFN)
+            self.assertEqual(data, b'\x78\x56\x34\x12')
+
+    def test_write_object_to_file(self):
+        obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000)
+        for v in range(marshal.version + 1):
+            _testcapi.pymarshal_write_object_to_file(obj, test_support.TESTFN, v)
+            with open(test_support.TESTFN, 'rb') as f:
+                data = f.read()
+            test_support.unlink(test_support.TESTFN)
+            self.assertEqual(marshal.loads(data), obj)
+
+    def test_read_short_from_file(self):
+        with open(test_support.TESTFN, 'wb') as f:
+            f.write(b'\x34\x12xxxx')
+        r, p = _testcapi.pymarshal_read_short_from_file(test_support.TESTFN)
+        test_support.unlink(test_support.TESTFN)
+        self.assertEqual(r, 0x1234)
+        self.assertEqual(p, 2)
+
+    def test_read_long_from_file(self):
+        with open(test_support.TESTFN, 'wb') as f:
+            f.write(b'\x78\x56\x34\x12xxxx')
+        r, p = _testcapi.pymarshal_read_long_from_file(test_support.TESTFN)
+        test_support.unlink(test_support.TESTFN)
+        self.assertEqual(r, 0x12345678)
+        self.assertEqual(p, 4)
+
+    def test_read_last_object_from_file(self):
+        obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
+        for v in range(marshal.version + 1):
+            data = marshal.dumps(obj, v)
+            with open(test_support.TESTFN, 'wb') as f:
+                f.write(data + b'xxxx')
+            r, p = _testcapi.pymarshal_read_last_object_from_file(test_support.TESTFN)
+            test_support.unlink(test_support.TESTFN)
+            self.assertEqual(r, obj)
+
+    def test_read_object_from_file(self):
+        obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
+        for v in range(marshal.version + 1):
+            data = marshal.dumps(obj, v)
+            with open(test_support.TESTFN, 'wb') as f:
+                f.write(data + b'xxxx')
+            r, p = _testcapi.pymarshal_read_object_from_file(test_support.TESTFN)
+            test_support.unlink(test_support.TESTFN)
+            self.assertEqual(r, obj)
+            self.assertEqual(p, len(data))
+
+
 def test_main():
     test_support.run_unittest(IntTestCase,
                               FloatTestCase,
@@ -325,6 +389,7 @@ def test_main():
                               ExceptionTestCase,
                               BugsTestCase,
                               LargeValuesTestCase,
+                              CAPI_TestCase,
                              )
 
 if __name__ == "__main__":
index 74a9ffb..fdd642b 100644 (file)
@@ -376,13 +376,14 @@ class MemoryTestMixin:
         # the module-level.
         import __main__
         PickleTestMemIO.__module__ = '__main__'
+        PickleTestMemIO.__qualname__ = PickleTestMemIO.__name__
         __main__.PickleTestMemIO = PickleTestMemIO
         submemio = PickleTestMemIO(buf, 80)
         submemio.seek(2)
 
         # We only support pickle protocol 2 and onward since we use extended
         # __reduce__ API of PEP 307 to provide pickling support.
-        for proto in range(2, pickle.HIGHEST_PROTOCOL):
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
             for obj in (memio, submemio):
                 obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))
                 self.assertEqual(obj.getvalue(), obj2.getvalue())
index 66973ed..a962ddc 100644 (file)
@@ -1385,43 +1385,44 @@ class MinidomTest(unittest.TestCase):
                     "  <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
                     "]><doc attr='value'> text\n"
                     "<?pi sample?> <!-- comment --> <e/> </doc>")
-        s = pickle.dumps(doc)
-        doc2 = pickle.loads(s)
-        stack = [(doc, doc2)]
-        while stack:
-            n1, n2 = stack.pop()
-            self.confirm(n1.nodeType == n2.nodeType
-                    and len(n1.childNodes) == len(n2.childNodes)
-                    and n1.nodeName == n2.nodeName
-                    and not n1.isSameNode(n2)
-                    and not n2.isSameNode(n1))
-            if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
-                len(n1.entities)
-                len(n2.entities)
-                len(n1.notations)
-                len(n2.notations)
-                self.confirm(len(n1.entities) == len(n2.entities)
-                        and len(n1.notations) == len(n2.notations))
-                for i in range(len(n1.notations)):
-                    # XXX this loop body doesn't seem to be executed?
-                    no1 = n1.notations.item(i)
-                    no2 = n1.notations.item(i)
-                    self.confirm(no1.name == no2.name
-                            and no1.publicId == no2.publicId
-                            and no1.systemId == no2.systemId)
-                    stack.append((no1, no2))
-                for i in range(len(n1.entities)):
-                    e1 = n1.entities.item(i)
-                    e2 = n2.entities.item(i)
-                    self.confirm(e1.notationName == e2.notationName
-                            and e1.publicId == e2.publicId
-                            and e1.systemId == e2.systemId)
-                    stack.append((e1, e2))
-            if n1.nodeType != Node.DOCUMENT_NODE:
-                self.confirm(n1.ownerDocument.isSameNode(doc)
-                        and n2.ownerDocument.isSameNode(doc2))
-            for i in range(len(n1.childNodes)):
-                stack.append((n1.childNodes[i], n2.childNodes[i]))
+        for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
+            s = pickle.dumps(doc, proto)
+            doc2 = pickle.loads(s)
+            stack = [(doc, doc2)]
+            while stack:
+                n1, n2 = stack.pop()
+                self.confirm(n1.nodeType == n2.nodeType
+                        and len(n1.childNodes) == len(n2.childNodes)
+                        and n1.nodeName == n2.nodeName
+                        and not n1.isSameNode(n2)
+                        and not n2.isSameNode(n1))
+                if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
+                    len(n1.entities)
+                    len(n2.entities)
+                    len(n1.notations)
+                    len(n2.notations)
+                    self.confirm(len(n1.entities) == len(n2.entities)
+                            and len(n1.notations) == len(n2.notations))
+                    for i in range(len(n1.notations)):
+                        # XXX this loop body doesn't seem to be executed?
+                        no1 = n1.notations.item(i)
+                        no2 = n1.notations.item(i)
+                        self.confirm(no1.name == no2.name
+                                and no1.publicId == no2.publicId
+                                and no1.systemId == no2.systemId)
+                        stack.append((no1, no2))
+                    for i in range(len(n1.entities)):
+                        e1 = n1.entities.item(i)
+                        e2 = n2.entities.item(i)
+                        self.confirm(e1.notationName == e2.notationName
+                                and e1.publicId == e2.publicId
+                                and e1.systemId == e2.systemId)
+                        stack.append((e1, e2))
+                if n1.nodeType != Node.DOCUMENT_NODE:
+                    self.confirm(n1.ownerDocument.isSameNode(doc)
+                            and n2.ownerDocument.isSameNode(doc2))
+                for i in range(len(n1.childNodes)):
+                    stack.append((n1.childNodes[i], n2.childNodes[i]))
 
     def testSerializeCommentNodeWithDoubleHyphen(self):
         doc = create_doc_without_doctype()
index 8aca381..5b61e7e 100644 (file)
@@ -43,6 +43,13 @@ class Test_MultibyteCodec(unittest.TestCase):
         self.assertRaises(IndexError, dec,
                           'apple\x92ham\x93spam', 'test.cjktest')
 
+    def test_errorcallback_custom_ignore(self):
+        # Issue #23215: MemoryError with custom error handlers and multibyte codecs
+        data = 100 * unichr(0xdc00)
+        codecs.register_error("test.ignore", codecs.ignore_errors)
+        for enc in ALL_CJKENCODINGS:
+            self.assertEqual(data.encode(enc, "test.ignore"), b'')
+
     def test_codingspec(self):
         for enc in ALL_CJKENCODINGS:
             code = '# coding: {}\n'.format(enc)
@@ -72,7 +79,7 @@ class Test_IncrementalEncoder(unittest.TestCase):
         self.assertEqual(encoder.reset(), None)
 
     def test_stateful(self):
-        # jisx0213 encoder is stateful for a few codepoints. eg)
+        # jisx0213 encoder is stateful for a few code points. eg)
         #   U+00E6 => A9DC
         #   U+00E6 U+0300 => ABC4
         #   U+0300 => ABDC
index c5dcfa3..1631e46 100644 (file)
@@ -20,7 +20,7 @@ class TestBase:
     roundtriptest   = 1    # set if roundtrip is possible with unicode
     has_iso10646    = 0    # set if this encoding contains whole iso10646 map
     xmlcharnametest = None # string to test xmlcharrefreplace
-    unmappedunicode = u'\udeee' # a unicode codepoint that is not mapped.
+    unmappedunicode = u'\udeee' # a unicode code point that is not mapped.
 
     def setUp(self):
         if self.codec is None:
index 42f6dd9..c66727c 100644 (file)
@@ -620,6 +620,26 @@ class _TestQueue(BaseTestCase):
         for p in workers:
             p.join()
 
+    def test_no_import_lock_contention(self):
+        with test_support.temp_cwd():
+            module_name = 'imported_by_an_imported_module'
+            with open(module_name + '.py', 'w') as f:
+                f.write("""if 1:
+                    import multiprocessing
+
+                    q = multiprocessing.Queue()
+                    q.put('knock knock')
+                    q.get(timeout=3)
+                    q.close()
+                """)
+
+            with test_support.DirsOnSysPath(os.getcwd()):
+                try:
+                    __import__(module_name)
+                except Queue.Empty:
+                    self.fail("Probable regression on import lock contention;"
+                              " see Issue #22853")
+
 #
 #
 #
@@ -1102,6 +1122,15 @@ class _TestContainers(BaseTestCase):
 def sqr(x, wait=0.0):
     time.sleep(wait)
     return x*x
+
+class SayWhenError(ValueError): pass
+
+def exception_throwing_generator(total, when):
+    for i in range(total):
+        if i == when:
+            raise SayWhenError("Somebody said when")
+        yield i
+
 class _TestPool(BaseTestCase):
 
     def test_apply(self):
@@ -1157,6 +1186,25 @@ class _TestPool(BaseTestCase):
             self.assertEqual(it.next(), i*i)
         self.assertRaises(StopIteration, it.next)
 
+    def test_imap_handle_iterable_exception(self):
+        if self.TYPE == 'manager':
+            self.skipTest('test not appropriate for {}'.format(self.TYPE))
+
+        it = self.pool.imap(sqr, exception_throwing_generator(10, 3), 1)
+        for i in range(3):
+            self.assertEqual(next(it), i*i)
+        self.assertRaises(SayWhenError, it.next)
+
+        # SayWhenError seen at start of problematic chunk's results
+        it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 2)
+        for i in range(6):
+            self.assertEqual(next(it), i*i)
+        self.assertRaises(SayWhenError, it.next)
+        it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 4)
+        for i in range(4):
+            self.assertEqual(next(it), i*i)
+        self.assertRaises(SayWhenError, it.next)
+
     def test_imap_unordered(self):
         it = self.pool.imap_unordered(sqr, range(1000))
         self.assertEqual(sorted(it), map(sqr, range(1000)))
@@ -1164,6 +1212,31 @@ class _TestPool(BaseTestCase):
         it = self.pool.imap_unordered(sqr, range(1000), chunksize=53)
         self.assertEqual(sorted(it), map(sqr, range(1000)))
 
+    def test_imap_unordered_handle_iterable_exception(self):
+        if self.TYPE == 'manager':
+            self.skipTest('test not appropriate for {}'.format(self.TYPE))
+
+        it = self.pool.imap_unordered(sqr,
+                                      exception_throwing_generator(10, 3),
+                                      1)
+        expected_values = map(sqr, range(10))
+        with self.assertRaises(SayWhenError):
+            # imap_unordered makes it difficult to anticipate the SayWhenError
+            for i in range(10):
+                value = next(it)
+                self.assertIn(value, expected_values)
+                expected_values.remove(value)
+
+        it = self.pool.imap_unordered(sqr,
+                                      exception_throwing_generator(20, 7),
+                                      2)
+        expected_values = map(sqr, range(20))
+        with self.assertRaises(SayWhenError):
+            for i in range(20):
+                value = next(it)
+                self.assertIn(value, expected_values)
+                expected_values.remove(value)
+
     def test_make_pool(self):
         self.assertRaises(ValueError, multiprocessing.Pool, -1)
         self.assertRaises(ValueError, multiprocessing.Pool, 0)
@@ -1371,6 +1444,16 @@ SERIALIZER = 'xmlrpclib'
 class _TestRemoteManager(BaseTestCase):
 
     ALLOWED_TYPES = ('manager',)
+    values = ['hello world', None, True, 2.25,
+              #'hall\xc3\xa5 v\xc3\xa4rlden'] # UTF-8
+              ]
+    result = values[:]
+    if test_support.have_unicode:
+        #result[-1] = u'hall\xe5 v\xe4rlden'
+        uvalue = test_support.u(r'\u043f\u0440\u0438\u0432\u0456\u0442 '
+                                r'\u0441\u0432\u0456\u0442')
+        values.append(uvalue)
+        result.append(uvalue)
 
     @classmethod
     def _putter(cls, address, authkey):
@@ -1379,7 +1462,8 @@ class _TestRemoteManager(BaseTestCase):
             )
         manager.connect()
         queue = manager.get_queue()
-        queue.put(('hello world', None, True, 2.25))
+        # Note that xmlrpclib will deserialize object as a list not a tuple
+        queue.put(tuple(cls.values))
 
     def test_remote(self):
         authkey = os.urandom(32)
@@ -1399,8 +1483,7 @@ class _TestRemoteManager(BaseTestCase):
         manager2.connect()
         queue = manager2.get_queue()
 
-        # Note that xmlrpclib will deserialize object as a list not a tuple
-        self.assertEqual(queue.get(), ['hello world', None, True, 2.25])
+        self.assertEqual(queue.get(), self.result)
 
         # Because we are using xmlrpclib for serialization instead of
         # pickle this will cause a serialization error.
@@ -2392,12 +2475,12 @@ class TestNoForkBomb(unittest.TestCase):
         name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py')
         if WIN32:
             rc, out, err = test.script_helper.assert_python_failure(name)
-            self.assertEqual('', out.decode('ascii'))
-            self.assertIn('RuntimeError', err.decode('ascii'))
+            self.assertEqual(out, '')
+            self.assertIn('RuntimeError', err)
         else:
             rc, out, err = test.script_helper.assert_python_ok(name)
-            self.assertEqual('123', out.decode('ascii').rstrip())
-            self.assertEqual('', err.decode('ascii'))
+            self.assertEqual(out.rstrip(), '123')
+            self.assertEqual(err, '')
 
 #
 # Issue 12098: check sys.flags of child matches that for parent
@@ -2421,6 +2504,7 @@ class TestFlags(unittest.TestCase):
         flags = (tuple(sys.flags), grandchild_flags)
         print(json.dumps(flags))
 
+    @test_support.requires_unicode  # XXX json needs unicode support
     def test_flags(self):
         import json, subprocess
         # start child process using unusual flags
index 7b5f7bb..b9a4c90 100644 (file)
@@ -69,8 +69,9 @@ class TestNtpath(unittest.TestCase):
                ('', '\\\\conky\\\\mountpoint\\foo\\bar'))
         tester('ntpath.splitunc("//conky//mountpoint/foo/bar")',
                ('', '//conky//mountpoint/foo/bar'))
-        self.assertEqual(ntpath.splitunc(u'//conky/MOUNTPO\u0130NT/foo/bar'),
-                         (u'//conky/MOUNTPO\u0130NT', u'/foo/bar'))
+        if test_support.have_unicode:
+            self.assertEqual(ntpath.splitunc(u'//conky/MOUNTPO%cNT/foo/bar' % 0x0130),
+                             (u'//conky/MOUNTPO%cNT' % 0x0130, u'/foo/bar'))
 
     def test_split(self):
         tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
@@ -205,6 +206,7 @@ class TestNtpath(unittest.TestCase):
             tester('ntpath.expandvars("%?bar%")', "%?bar%")
             tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
             tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
+            tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")
 
     @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII')
     def test_expandvars_nonascii(self):
@@ -281,13 +283,14 @@ class TestNtpath(unittest.TestCase):
             tester('ntpath.abspath("C:\\")', "C:\\")
 
     def test_relpath(self):
-        currentdir = os.path.split(os.getcwd())[-1]
         tester('ntpath.relpath("a")', 'a')
         tester('ntpath.relpath(os.path.abspath("a"))', 'a')
         tester('ntpath.relpath("a/b")', 'a\\b')
         tester('ntpath.relpath("../a/b")', '..\\a\\b')
-        tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
-        tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
+        with test_support.temp_cwd(test_support.TESTFN) as cwd_dir:
+            currentdir = os.path.basename(cwd_dir)
+            tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
+            tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
         tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
         tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
         tester('ntpath.relpath("a", "a")', '.')
index 023ebf4..6c7ea7a 100644 (file)
@@ -9,6 +9,8 @@ import warnings
 import sys
 import signal
 import subprocess
+import sysconfig
+import textwrap
 import time
 try:
     import resource
@@ -567,6 +569,12 @@ class URandomTests (unittest.TestCase):
         data2 = self.get_urandom_subprocess(16)
         self.assertNotEqual(data1, data2)
 
+
+HAVE_GETENTROPY = (sysconfig.get_config_var('HAVE_GETENTROPY') == 1)
+
+@unittest.skipIf(HAVE_GETENTROPY,
+                 "getentropy() does not use a file descriptor")
+class URandomFDTests(unittest.TestCase):
     @unittest.skipUnless(resource, "test requires the resource module")
     def test_urandom_failure(self):
         # Check urandom() failing when it is not able to open /dev/random.
@@ -881,6 +889,7 @@ def test_main():
         MakedirTests,
         DevNullTests,
         URandomTests,
+        URandomFDTests,
         ExecvpeTests,
         Win32ErrorTests,
         TestInvalidFD,
index 559f756..b6dd2b7 100644 (file)
@@ -63,6 +63,7 @@ class PdbTestCase(unittest.TestCase):
         with open('bar.py', 'w') as f:
             f.write(textwrap.dedent(bar))
         self.addCleanup(test_support.unlink, 'bar.py')
+        self.addCleanup(test_support.unlink, 'bar.pyc')
         stdout, stderr = self.run_pdb(script, commands)
         self.assertTrue(
             any('main.py(5)foo()->None' in l for l in stdout.splitlines()),
index 5ff280d..133cab7 100644 (file)
@@ -26,6 +26,7 @@ class TestTemplate(unittest.TestCase):
         self.assertEqual(s.substitute(dict(who='tim', what='ham')),
                          'tim likes to eat a bag of ham worth $100')
         self.assertRaises(KeyError, s.substitute, dict(who='tim'))
+        self.assertRaises(TypeError, Template.substitute)
 
     def test_regular_templates_with_braces(self):
         s = Template('$who likes ${what} for ${meal}')
@@ -178,6 +179,9 @@ class TestTemplate(unittest.TestCase):
         eq(s.substitute(dict(mapping='one'), mapping='two'),
            'the mapping is two')
 
+        s = Template('the self is $self')
+        eq(s.substitute(self='bozo'), 'the self is bozo')
+
     def test_keyword_arguments_safe(self):
         eq = self.assertEqual
         raises = self.assertRaises
@@ -196,6 +200,9 @@ class TestTemplate(unittest.TestCase):
         raises(TypeError, s.substitute, d, {})
         raises(TypeError, s.safe_substitute, d, {})
 
+        s = Template('the self is $self')
+        eq(s.safe_substitute(self='bozo'), 'the self is bozo')
+
     def test_delimiter_override(self):
         eq = self.assertEqual
         raises = self.assertRaises
index 3f44aa3..9810c77 100644 (file)
@@ -261,6 +261,40 @@ class PosixTester(unittest.TestCase):
     def test_stat(self):
         self.assertTrue(posix.stat(test_support.TESTFN))
 
+    @unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
+    @unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
+    def test_makedev(self):
+        st = posix.stat(test_support.TESTFN)
+        dev = st.st_dev
+        self.assertIsInstance(dev, (int, long))
+        self.assertGreaterEqual(dev, 0)
+
+        major = posix.major(dev)
+        self.assertIsInstance(major, (int, long))
+        self.assertGreaterEqual(major, 0)
+        self.assertEqual(posix.major(int(dev)), major)
+        self.assertEqual(posix.major(long(dev)), major)
+        self.assertRaises(TypeError, posix.major, float(dev))
+        self.assertRaises(TypeError, posix.major)
+        self.assertRaises((ValueError, OverflowError), posix.major, -1)
+
+        minor = posix.minor(dev)
+        self.assertIsInstance(minor, (int, long))
+        self.assertGreaterEqual(minor, 0)
+        self.assertEqual(posix.minor(int(dev)), minor)
+        self.assertEqual(posix.minor(long(dev)), minor)
+        self.assertRaises(TypeError, posix.minor, float(dev))
+        self.assertRaises(TypeError, posix.minor)
+        self.assertRaises((ValueError, OverflowError), posix.minor, -1)
+
+        self.assertEqual(posix.makedev(major, minor), dev)
+        self.assertEqual(posix.makedev(int(major), int(minor)), dev)
+        self.assertEqual(posix.makedev(long(major), long(minor)), dev)
+        self.assertRaises(TypeError, posix.makedev, float(major), minor)
+        self.assertRaises(TypeError, posix.makedev, major, float(minor))
+        self.assertRaises(TypeError, posix.makedev, major)
+        self.assertRaises(TypeError, posix.makedev)
+
     def _test_all_chown_common(self, chown_func, first_param, stat_func):
         """Common code for chown, fchown and lchown tests."""
         def check_stat(uid, gid):
index f74dc14..13381e5 100644 (file)
@@ -1,7 +1,9 @@
 import unittest
 from test import test_support, test_genericpath
 
-import posixpath, os
+import posixpath
+import os
+import sys
 from posixpath import realpath, abspath, dirname, basename
 
 # An absolute path to a temporary filename for testing. We can't rely on TESTFN
@@ -409,6 +411,21 @@ class PosixPathTest(unittest.TestCase):
         finally:
             os.getcwd = real_getcwd
 
+    @test_support.requires_unicode
+    def test_expandvars_nonascii_word(self):
+        encoding = sys.getfilesystemencoding()
+        # Non-ASCII word characters
+        letters = test_support.u(r'\xe6\u0130\u0141\u03c6\u041a\u05d0\u062a\u0e01')
+        uwnonascii = letters.encode(encoding, 'ignore').decode(encoding)[:3]
+        swnonascii = uwnonascii.encode(encoding)
+        if not swnonascii:
+            self.skipTest('Needs non-ASCII word characters')
+        with test_support.EnvironmentVarGuard() as env:
+            env.clear()
+            env[swnonascii] = 'baz' + swnonascii
+            self.assertEqual(posixpath.expandvars(u'$%s bar' % uwnonascii),
+                             u'baz%s bar' % uwnonascii)
+
 
 class PosixCommonTest(test_genericpath.CommonTest):
     pathmodule = posixpath
index c11c06b..6cfe7e7 100644 (file)
@@ -3,6 +3,7 @@ import sys
 import difflib
 import __builtin__
 import re
+import py_compile
 import pydoc
 import contextlib
 import inspect
@@ -382,6 +383,36 @@ class PydocDocTest(unittest.TestCase):
         self.assertEqual(stripid("<type 'exceptions.Exception'>"),
                          "<type 'exceptions.Exception'>")
 
+    def test_synopsis(self):
+        with test.test_support.temp_cwd() as test_dir:
+            init_path = os.path.join(test_dir, 'dt.py')
+            with open(init_path, 'w') as fobj:
+                fobj.write('''\
+"""
+my doc
+
+second line
+"""
+foo = 1
+''')
+            py_compile.compile(init_path)
+            synopsis = pydoc.synopsis(init_path, {})
+            self.assertEqual(synopsis, 'my doc')
+
+    @unittest.skipIf(sys.flags.optimize >= 2,
+                     'Docstrings are omitted with -OO and above')
+    def test_synopsis_sourceless_empty_doc(self):
+        with test.test_support.temp_cwd() as test_dir:
+            init_path = os.path.join(test_dir, 'foomod42.py')
+            cached_path = os.path.join(test_dir, 'foomod42.pyc')
+            with open(init_path, 'w') as fobj:
+                fobj.write("foo = 1")
+            py_compile.compile(init_path)
+            synopsis = pydoc.synopsis(init_path, {})
+            self.assertIsNone(synopsis)
+            synopsis_cached = pydoc.synopsis(cached_path, {})
+            self.assertIsNone(synopsis_cached)
+
 
 class PydocImportTest(PydocBaseTest):
 
index 1a5a86b..250f443 100644 (file)
@@ -140,11 +140,12 @@ class TestBasicOps(unittest.TestCase):
             self.assertEqual(y1, y2)
 
     def test_pickling(self):
-        state = pickle.dumps(self.gen)
-        origseq = [self.gen.random() for i in xrange(10)]
-        newgen = pickle.loads(state)
-        restoredseq = [newgen.random() for i in xrange(10)]
-        self.assertEqual(origseq, restoredseq)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            state = pickle.dumps(self.gen, proto)
+            origseq = [self.gen.random() for i in xrange(10)]
+            newgen = pickle.loads(state)
+            restoredseq = [newgen.random() for i in xrange(10)]
+            self.assertEqual(origseq, restoredseq)
 
     def test_bug_1727780(self):
         # verify that version-2-pickles can be loaded
@@ -226,7 +227,8 @@ class SystemRandom_TestBasicOps(TestBasicOps):
         self.assertEqual(self.gen.gauss_next, None)
 
     def test_pickling(self):
-        self.assertRaises(NotImplementedError, pickle.dumps, self.gen)
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
 
     def test_53_bits_per_float(self):
         # This should pass whenever a C double has 53 bit precision.
index 5e2914d..588042a 100644 (file)
@@ -1,7 +1,9 @@
 # -*- coding: utf-8 -*-
-from test.test_support import verbose, run_unittest, import_module
-from test.test_support import precisionbigmemtest, _2G, cpython_only
-from test.test_support import captured_stdout, have_unicode, requires_unicode, u
+from test.test_support import (
+    verbose, run_unittest, import_module,
+    precisionbigmemtest, _2G, cpython_only,
+    captured_stdout, have_unicode, requires_unicode, u,
+    check_warnings)
 import locale
 import re
 from re import Scanner
@@ -449,7 +451,7 @@ class ReTests(unittest.TestCase):
         self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
                          "a\n\nb")
 
-    def test_non_consuming(self):
+    def test_lookahead(self):
         self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a")
         self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a")
         self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a")
@@ -463,6 +465,41 @@ class ReTests(unittest.TestCase):
         self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
         self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
 
+        # Group reference.
+        self.assertTrue(re.match(r'(a)b(?=\1)a', 'aba'))
+        self.assertIsNone(re.match(r'(a)b(?=\1)c', 'abac'))
+        # Named group reference.
+        self.assertTrue(re.match(r'(?P<g>a)b(?=(?P=g))a', 'aba'))
+        self.assertIsNone(re.match(r'(?P<g>a)b(?=(?P=g))c', 'abac'))
+        # Conditional group reference.
+        self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
+        self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(2)c|x))c', 'abc'))
+        self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(2)x|c))c', 'abc'))
+        self.assertIsNone(re.match(r'(?:(a)|(x))b(?=(?(1)b|x))c', 'abc'))
+        self.assertTrue(re.match(r'(?:(a)|(x))b(?=(?(1)c|x))c', 'abc'))
+        # Group used before defined.
+        self.assertTrue(re.match(r'(a)b(?=(?(2)x|c))(c)', 'abc'))
+        self.assertIsNone(re.match(r'(a)b(?=(?(2)b|x))(c)', 'abc'))
+        self.assertTrue(re.match(r'(a)b(?=(?(1)c|x))(c)', 'abc'))
+
+    def test_lookbehind(self):
+        self.assertTrue(re.match(r'ab(?<=b)c', 'abc'))
+        self.assertIsNone(re.match(r'ab(?<=c)c', 'abc'))
+        self.assertIsNone(re.match(r'ab(?<!b)c', 'abc'))
+        self.assertTrue(re.match(r'ab(?<!c)c', 'abc'))
+        # Group reference.
+        with check_warnings(('', RuntimeWarning)):
+            re.compile(r'(a)a(?<=\1)c')
+        # Named group reference.
+        with check_warnings(('', RuntimeWarning)):
+            re.compile(r'(?P<g>a)a(?<=(?P=g))c')
+        # Conditional group reference.
+        with check_warnings(('', RuntimeWarning)):
+            re.compile(r'(a)b(?<=(?(1)b|x))c')
+        # Group used before defined.
+        with check_warnings(('', RuntimeWarning)):
+            re.compile(r'(a)b(?<=(?(2)b|x))(c)')
+
     def test_ignore_case(self):
         self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
         self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
index e009952..588043e 100644 (file)
@@ -15,9 +15,9 @@ class TestHistoryManipulation (unittest.TestCase):
     That's why the tests cover only a small subset of the interface.
     """
 
-    @unittest.skipIf(not hasattr(readline, 'clear_history'),
-                     "The history update test cannot be run because the "
-                     "clear_history method is not available.")
+    @unittest.skipUnless(hasattr(readline, "clear_history"),
+                         "The history update test cannot be run because the "
+                         "clear_history method is not available.")
     def testHistoryUpdates(self):
         readline.clear_history()
 
index d8a0280..cdd8c9c 100644 (file)
@@ -248,6 +248,12 @@ A test message.
         eq(rfc822.quote('foo\\wacky"name'), 'foo\\\\wacky\\"name')
         eq(rfc822.unquote('"foo\\\\wacky\\"name"'), 'foo\\wacky"name')
 
+    def test_invalid_headers(self):
+        eq = self.assertEqual
+        msg = self.create_message("First: val\n: otherval\nSecond: val2\n")
+        eq(msg.getheader('First'), 'val')
+        eq(msg.getheader('Second'), 'val2')
+
 
 def test_main():
     test_support.run_unittest(MessageTestCase)
index 86638a2..a4228dc 100644 (file)
@@ -9,16 +9,17 @@ except SAXReaderNotAvailable:
     # don't try to test this module if we cannot create a parser
     raise ImportError("no XML parsers available")
 from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \
-                             XMLFilterBase
+                             XMLFilterBase, prepare_input_source
 from xml.sax.expatreader import create_parser
 from xml.sax.handler import feature_namespaces
 from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
 from cStringIO import StringIO
 import io
+import gc
 import os.path
 import shutil
 import test.test_support as support
-from test.test_support import findfile, run_unittest
+from test.test_support import findfile, run_unittest, TESTFN
 import unittest
 
 TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
@@ -90,6 +91,111 @@ class XmlTestBase(unittest.TestCase):
         self.assertEqual(attrs["attr"], "val")
         self.assertEqual(attrs.getQNameByName("attr"), "attr")
 
+
+def xml_unicode(doc, encoding=None):
+    if encoding is None:
+        return doc
+    return u'<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc)
+
+def xml_bytes(doc, encoding, decl_encoding=Ellipsis):
+    if decl_encoding is Ellipsis:
+        decl_encoding = encoding
+    return xml_unicode(doc, decl_encoding).encode(encoding, 'xmlcharrefreplace')
+
+def make_xml_file(doc, encoding, decl_encoding=Ellipsis):
+    if decl_encoding is Ellipsis:
+        decl_encoding = encoding
+    with io.open(TESTFN, 'w', encoding=encoding, errors='xmlcharrefreplace') as f:
+        f.write(xml_unicode(doc, decl_encoding))
+
+
+class ParseTest(unittest.TestCase):
+    data = support.u(r'<money value="$\xa3\u20ac\U0001017b">'
+                     r'$\xa3\u20ac\U0001017b</money>')
+
+    def tearDown(self):
+        support.unlink(TESTFN)
+
+    def check_parse(self, f):
+        from xml.sax import parse
+        result = StringIO()
+        parse(f, XMLGenerator(result, 'utf-8'))
+        self.assertEqual(result.getvalue(), xml_bytes(self.data, 'utf-8'))
+
+    def test_parse_bytes(self):
+        # UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
+        # UTF-16 is autodetected
+        encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be')
+        for encoding in encodings:
+            self.check_parse(io.BytesIO(xml_bytes(self.data, encoding)))
+            make_xml_file(self.data, encoding)
+            self.check_parse(TESTFN)
+            with io.open(TESTFN, 'rb') as f:
+                self.check_parse(f)
+            self.check_parse(io.BytesIO(xml_bytes(self.data, encoding, None)))
+            make_xml_file(self.data, encoding, None)
+            self.check_parse(TESTFN)
+            with io.open(TESTFN, 'rb') as f:
+                self.check_parse(f)
+        # accept UTF-8 with BOM
+        self.check_parse(io.BytesIO(xml_bytes(self.data, 'utf-8-sig', 'utf-8')))
+        make_xml_file(self.data, 'utf-8-sig', 'utf-8')
+        self.check_parse(TESTFN)
+        with io.open(TESTFN, 'rb') as f:
+            self.check_parse(f)
+        self.check_parse(io.BytesIO(xml_bytes(self.data, 'utf-8-sig', None)))
+        make_xml_file(self.data, 'utf-8-sig', None)
+        self.check_parse(TESTFN)
+        with io.open(TESTFN, 'rb') as f:
+            self.check_parse(f)
+        # accept data with declared encoding
+        self.check_parse(io.BytesIO(xml_bytes(self.data, 'iso-8859-1')))
+        make_xml_file(self.data, 'iso-8859-1')
+        self.check_parse(TESTFN)
+        with io.open(TESTFN, 'rb') as f:
+            self.check_parse(f)
+        # fail on non-UTF-8 incompatible data without declared encoding
+        with self.assertRaises(SAXException):
+            self.check_parse(io.BytesIO(xml_bytes(self.data, 'iso-8859-1', None)))
+        make_xml_file(self.data, 'iso-8859-1', None)
+        with self.assertRaises(SAXException):
+            self.check_parse(TESTFN)
+        with io.open(TESTFN, 'rb') as f:
+            with self.assertRaises(SAXException):
+                self.check_parse(f)
+
+    def test_parse_InputSource(self):
+        # accept data without declared but with explicitly specified encoding
+        make_xml_file(self.data, 'iso-8859-1', None)
+        with io.open(TESTFN, 'rb') as f:
+            input = InputSource()
+            input.setByteStream(f)
+            input.setEncoding('iso-8859-1')
+            self.check_parse(input)
+
+    def check_parseString(self, s):
+        from xml.sax import parseString
+        result = StringIO()
+        parseString(s, XMLGenerator(result, 'utf-8'))
+        self.assertEqual(result.getvalue(), xml_bytes(self.data, 'utf-8'))
+
+    def test_parseString_bytes(self):
+        # UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
+        # UTF-16 is autodetected
+        encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be')
+        for encoding in encodings:
+            self.check_parseString(xml_bytes(self.data, encoding))
+            self.check_parseString(xml_bytes(self.data, encoding, None))
+        # accept UTF-8 with BOM
+        self.check_parseString(xml_bytes(self.data, 'utf-8-sig', 'utf-8'))
+        self.check_parseString(xml_bytes(self.data, 'utf-8-sig', None))
+        # accept data with declared encoding
+        self.check_parseString(xml_bytes(self.data, 'iso-8859-1'))
+        # fail on non-UTF-8 incompatible data without declared encoding
+        with self.assertRaises(SAXException):
+            self.check_parseString(xml_bytes(self.data, 'iso-8859-1', None))
+
+
 class MakeParserTest(unittest.TestCase):
     def test_make_parser2(self):
         # Creating parsers several times in a row should succeed.
@@ -167,6 +273,60 @@ class SaxutilsTest(unittest.TestCase):
         p = make_parser(['xml.parsers.no_such_parser'])
 
 
+class PrepareInputSourceTest(unittest.TestCase):
+
+    def setUp(self):
+        self.file = support.TESTFN
+        with open(self.file, "w") as tmp:
+            tmp.write("This was read from a file.")
+
+    def tearDown(self):
+        support.unlink(self.file)
+
+    def make_byte_stream(self):
+        return io.BytesIO(b"This is a byte stream.")
+
+    def checkContent(self, stream, content):
+        self.assertIsNotNone(stream)
+        self.assertEqual(stream.read(), content)
+        stream.close()
+
+
+    def test_byte_stream(self):
+        # If the source is an InputSource that does not have a character
+        # stream but does have a byte stream, use the byte stream.
+        src = InputSource(self.file)
+        src.setByteStream(self.make_byte_stream())
+        prep = prepare_input_source(src)
+        self.assertIsNone(prep.getCharacterStream())
+        self.checkContent(prep.getByteStream(),
+                          b"This is a byte stream.")
+
+    def test_system_id(self):
+        # If the source is an InputSource that has neither a character
+        # stream nor a byte stream, open the system ID.
+        src = InputSource(self.file)
+        prep = prepare_input_source(src)
+        self.assertIsNone(prep.getCharacterStream())
+        self.checkContent(prep.getByteStream(),
+                          b"This was read from a file.")
+
+    def test_string(self):
+        # If the source is a string, use it as a system ID and open it.
+        prep = prepare_input_source(self.file)
+        self.assertIsNone(prep.getCharacterStream())
+        self.checkContent(prep.getByteStream(),
+                          b"This was read from a file.")
+
+    def test_binary_file(self):
+        # If the source is a binary file-like object, use it as a byte
+        # stream.
+        prep = prepare_input_source(self.make_byte_stream())
+        self.assertIsNone(prep.getCharacterStream())
+        self.checkContent(prep.getByteStream(),
+                          b"This is a byte stream.")
+
+
 # ===== XMLGenerator
 
 start = '<?xml version="1.0" encoding="iso-8859-1"?>\n'
@@ -481,7 +641,7 @@ class ExpatReaderTest(XmlTestBase):
 
     # ===== XMLReader support
 
-    def test_expat_file(self):
+    def test_expat_binary_file(self):
         parser = create_parser()
         result = StringIO()
         xmlgen = XMLGenerator(result)
@@ -660,7 +820,7 @@ class ExpatReaderTest(XmlTestBase):
 
         self.assertEqual(result.getvalue(), xml_test_out)
 
-    def test_expat_inpsource_stream(self):
+    def test_expat_inpsource_byte_stream(self):
         parser = create_parser()
         result = StringIO()
         xmlgen = XMLGenerator(result)
@@ -773,6 +933,8 @@ class ErrorReportingTest(unittest.TestCase):
         parser = create_parser()
         parser.setContentHandler(ContentHandler()) # do nothing
         self.assertRaises(SAXParseException, parser.parse, StringIO("<foo>"))
+        self.assertEqual(parser.getColumnNumber(), 5)
+        self.assertEqual(parser.getLineNumber(), 1)
 
     def test_sax_parse_exception_str(self):
         # pass various values from a locator to the SAXParseException to
@@ -895,7 +1057,9 @@ class XmlReaderTest(XmlTestBase):
 
 def test_main():
     run_unittest(MakeParserTest,
+                 ParseTest,
                  SaxutilsTest,
+                 PrepareInputSourceTest,
                  StringXmlgenTest,
                  BytesIOXmlgenTest,
                  WriterXmlgenTest,
index 610be7c..dd65202 100644 (file)
@@ -233,7 +233,7 @@ class TestJointOps(unittest.TestCase):
             self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup))
             if type(self.s) not in (set, frozenset):
                 self.s.x = 10
-                p = pickle.dumps(self.s)
+                p = pickle.dumps(self.s, i)
                 dup = pickle.loads(p)
                 self.assertEqual(self.s.x, dup.x)
 
@@ -786,10 +786,11 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(setiter.__length_hint__(), len(self.set))
 
     def test_pickling(self):
-        p = pickle.dumps(self.set)
-        copy = pickle.loads(p)
-        self.assertEqual(self.set, copy,
-                         "%s != %s" % (self.set, copy))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            p = pickle.dumps(self.set, proto)
+            copy = pickle.loads(p)
+            self.assertEqual(self.set, copy,
+                             "%s != %s" % (self.set, copy))
 
 #------------------------------------------------------------------------------
 
index 319bdcb..0a89908 100644 (file)
@@ -75,10 +75,11 @@ class TestBasicOps(unittest.TestCase):
             self.assertIn(v, self.values)
 
     def test_pickling(self):
-        p = pickle.dumps(self.set)
-        copy = pickle.loads(p)
-        self.assertEqual(self.set, copy,
-                         "%s != %s" % (self.set, copy))
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+            p = pickle.dumps(self.set, proto)
+            copy = pickle.loads(p)
+            self.assertEqual(self.set, copy,
+                             "%s != %s" % (self.set, copy))
 
 #------------------------------------------------------------------------------
 
index 0e81145..bcabe75 100644 (file)
@@ -581,6 +581,29 @@ class TestShutil(unittest.TestCase):
         finally:
             unregister_archive_format('xxx')
 
+    def test_make_tarfile_in_curdir(self):
+        # Issue #21280
+        root_dir = self.mkdtemp()
+        saved_dir = os.getcwd()
+        try:
+            os.chdir(root_dir)
+            self.assertEqual(make_archive('test', 'tar'), 'test.tar')
+            self.assertTrue(os.path.isfile('test.tar'))
+        finally:
+            os.chdir(saved_dir)
+
+    @unittest.skipUnless(zlib, "Requires zlib")
+    def test_make_zipfile_in_curdir(self):
+        # Issue #21280
+        root_dir = self.mkdtemp()
+        saved_dir = os.getcwd()
+        try:
+            os.chdir(root_dir)
+            self.assertEqual(make_archive('test', 'zip'), 'test.zip')
+            self.assertTrue(os.path.isfile('test.zip'))
+        finally:
+            os.chdir(saved_dir)
+
     def test_register_archive_format(self):
 
         self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
index 46342cc..e58f55a 100644 (file)
@@ -66,7 +66,7 @@ BADKEY = data_file("badkey.pem")
 NOKIACERT = data_file("nokia.pem")
 NULLBYTECERT = data_file("nullbytecert.pem")
 
-DHFILE = data_file("dh512.pem")
+DHFILE = data_file("dh1024.pem")
 BYTES_DHFILE = DHFILE.encode(sys.getfilesystemencoding())
 
 
@@ -169,8 +169,9 @@ class BasicSocketTests(unittest.TestCase):
             sys.stdout.write("\n RAND_status is %d (%s)\n"
                              % (v, (v and "sufficient randomness") or
                                 "insufficient randomness"))
-        self.assertRaises(TypeError, ssl.RAND_egd, 1)
-        self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1)
+        if hasattr(ssl, 'RAND_egd'):
+            self.assertRaises(TypeError, ssl.RAND_egd, 1)
+            self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1)
         ssl.RAND_add("this is a random string", 75.0)
 
     def test_parse_cert(self):
@@ -274,7 +275,7 @@ class BasicSocketTests(unittest.TestCase):
         self.assertGreaterEqual(fix, 0)
         self.assertLess(fix, 256)
         self.assertGreaterEqual(patch, 0)
-        self.assertLessEqual(patch, 26)
+        self.assertLessEqual(patch, 63)
         self.assertGreaterEqual(status, 0)
         self.assertLessEqual(status, 15)
         # Version string as returned by {Open,Libre}SSL, the format might change
@@ -748,8 +749,9 @@ class ContextTests(unittest.TestCase):
                          "verify_flags need OpenSSL > 0.9.8")
     def test_verify_flags(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
-        # default value by OpenSSL
-        self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT)
+        # default value
+        tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
+        self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf)
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
         self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF)
         ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
@@ -1568,7 +1570,8 @@ else:
                 try:
                     self.sslconn = self.server.context.wrap_socket(
                         self.sock, server_side=True)
-                    self.server.selected_protocols.append(self.sslconn.selected_npn_protocol())
+                    self.server.selected_npn_protocols.append(self.sslconn.selected_npn_protocol())
+                    self.server.selected_alpn_protocols.append(self.sslconn.selected_alpn_protocol())
                 except socket.error as e:
                     # We treat ConnectionResetError as though it were an
                     # SSLError - OpenSSL on Ubuntu abruptly closes the
@@ -1677,7 +1680,8 @@ else:
         def __init__(self, certificate=None, ssl_version=None,
                      certreqs=None, cacerts=None,
                      chatty=True, connectionchatty=False, starttls_server=False,
-                     npn_protocols=None, ciphers=None, context=None):
+                     npn_protocols=None, alpn_protocols=None,
+                     ciphers=None, context=None):
             if context:
                 self.context = context
             else:
@@ -1692,6 +1696,8 @@ else:
                     self.context.load_cert_chain(certificate)
                 if npn_protocols:
                     self.context.set_npn_protocols(npn_protocols)
+                if alpn_protocols:
+                    self.context.set_alpn_protocols(alpn_protocols)
                 if ciphers:
                     self.context.set_ciphers(ciphers)
             self.chatty = chatty
@@ -1701,7 +1707,8 @@ else:
             self.port = support.bind_port(self.sock)
             self.flag = None
             self.active = False
-            self.selected_protocols = []
+            self.selected_npn_protocols = []
+            self.selected_alpn_protocols = []
             self.conn_errors = []
             threading.Thread.__init__(self)
             self.daemon = True
@@ -1926,11 +1933,13 @@ else:
                     'compression': s.compression(),
                     'cipher': s.cipher(),
                     'peercert': s.getpeercert(),
+                    'client_alpn_protocol': s.selected_alpn_protocol(),
                     'client_npn_protocol': s.selected_npn_protocol(),
                     'version': s.version(),
                 })
                 s.close()
-            stats['server_npn_protocols'] = server.selected_protocols
+            stats['server_alpn_protocols'] = server.selected_alpn_protocols
+            stats['server_npn_protocols'] = server.selected_npn_protocols
         return stats
 
     def try_protocol_combo(server_protocol, client_protocol, expect_success,
@@ -2056,7 +2065,8 @@ else:
             context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
             context.verify_mode = ssl.CERT_REQUIRED
             context.load_verify_locations(SIGNING_CA)
-            self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT)
+            tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
+            self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf)
 
             # VERIFY_DEFAULT should pass
             server = ThreadedEchoServer(context=server_context, chatty=True)
@@ -2786,6 +2796,55 @@ else:
             if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts:
                 self.fail("Non-DH cipher: " + cipher[0])
 
+        def test_selected_alpn_protocol(self):
+            # selected_alpn_protocol() is None unless ALPN is used.
+            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+            context.load_cert_chain(CERTFILE)
+            stats = server_params_test(context, context,
+                                       chatty=True, connectionchatty=True)
+            self.assertIs(stats['client_alpn_protocol'], None)
+
+        @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required")
+        def test_selected_alpn_protocol_if_server_uses_alpn(self):
+            # selected_alpn_protocol() is None unless ALPN is used by the client.
+            client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+            client_context.load_verify_locations(CERTFILE)
+            server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+            server_context.load_cert_chain(CERTFILE)
+            server_context.set_alpn_protocols(['foo', 'bar'])
+            stats = server_params_test(client_context, server_context,
+                                       chatty=True, connectionchatty=True)
+            self.assertIs(stats['client_alpn_protocol'], None)
+
+        @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test")
+        def test_alpn_protocols(self):
+            server_protocols = ['foo', 'bar', 'milkshake']
+            protocol_tests = [
+                (['foo', 'bar'], 'foo'),
+                (['bar', 'foo'], 'foo'),
+                (['milkshake'], 'milkshake'),
+                (['http/3.0', 'http/4.0'], None)
+            ]
+            for client_protocols, expected in protocol_tests:
+                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+                server_context.load_cert_chain(CERTFILE)
+                server_context.set_alpn_protocols(server_protocols)
+                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+                client_context.load_cert_chain(CERTFILE)
+                client_context.set_alpn_protocols(client_protocols)
+                stats = server_params_test(client_context, server_context,
+                                           chatty=True, connectionchatty=True)
+
+                msg = "failed trying %s (s) and %s (c).\n" \
+                      "was expecting %s, but got %%s from the %%s" \
+                          % (str(server_protocols), str(client_protocols),
+                             str(expected))
+                client_result = stats['client_alpn_protocol']
+                self.assertEqual(client_result, expected, msg % (client_result, "client"))
+                server_result = stats['server_alpn_protocols'][-1] \
+                    if len(stats['server_alpn_protocols']) else 'nothing'
+                self.assertEqual(server_result, expected, msg % (server_result, "server"))
+
         def test_selected_npn_protocol(self):
             # selected_npn_protocol() is None unless NPN is used
             context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
@@ -2897,7 +2956,7 @@ else:
             server_context, other_context, client_context = self.sni_contexts()
 
             def cb_raising(ssl_sock, server_name, initial_context):
-                1/0
+                1.0/0.0
             server_context.set_servername_callback(cb_raising)
 
             with self.assertRaises(ssl.SSLError) as cm, \
index e786ab6..fdb3253 100644 (file)
@@ -196,6 +196,18 @@ class ModuleTest(unittest.TestCase):
         self.assertRaises(ValueError, format, '', '#')
         self.assertRaises(ValueError, format, '', '#20')
 
+    def test_format_keyword_arguments(self):
+        fmt = string.Formatter()
+        self.assertEqual(fmt.format("-{arg}-", arg='test'), '-test-')
+        self.assertRaises(KeyError, fmt.format, "-{arg}-")
+        self.assertEqual(fmt.format("-{self}-", self='test'), '-test-')
+        self.assertRaises(KeyError, fmt.format, "-{self}-")
+        self.assertEqual(fmt.format("-{format_string}-", format_string='test'),
+                         '-test-')
+        self.assertRaises(KeyError, fmt.format, "-{format_string}-")
+        self.assertEqual(fmt.format(arg='test', format_string="-{arg}-"),
+                         '-test-')
+
 class BytesAliasTest(unittest.TestCase):
 
     def test_builtin(self):
index 15bdf87..f6db89e 100644 (file)
@@ -1,5 +1,5 @@
 # To fully test this module, we would need a copy of the stringprep tables.
-# Since we don't have them, this test checks only a few codepoints.
+# Since we don't have them, this test checks only a few code points.
 
 import unittest
 from test import test_support
index 66b9ab3..7a47f9e 100644 (file)
@@ -484,6 +484,24 @@ class CalculationTests(unittest.TestCase):
         test_helper((2006, 12, 31), "Last Sunday of 2006")
         test_helper((2006, 12, 24), "Second to last Sunday of 2006")
 
+    def test_week_0(self):
+        def check(value, format, *expected):
+            self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected)
+        check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, -3)
+        check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4)
+        check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, -2)
+        check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, -2)
+        check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, -1)
+        check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, -1)
+        check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 0)
+        check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 0)
+        check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1)
+        check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1)
+        check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2)
+        check('2015 0 5', '%Y %W %w', 2015, 1, 2, 0, 0, 0, 4, 2)
+        check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3)
+        check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3)
+
 
 class CacheTests(unittest.TestCase):
     """Test that caching works properly."""
index 4811974..fe56dcb 100644 (file)
@@ -433,24 +433,24 @@ class StructTest(unittest.TestCase):
             self.assertRaises(struct.error, s.unpack_from, data, i)
             self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
 
-    def test_pack_into(self):
+    def test_pack_into(self, cls=bytearray, tobytes=str):
         test_string = 'Reykjavik rocks, eow!'
-        writable_buf = array.array('c', ' '*100)
+        writable_buf = cls(' '*100)
         fmt = '21s'
         s = struct.Struct(fmt)
 
         # Test without offset
         s.pack_into(writable_buf, 0, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)]
+        from_buf = tobytes(writable_buf)[:len(test_string)]
         self.assertEqual(from_buf, test_string)
 
         # Test with offset.
         s.pack_into(writable_buf, 10, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)+10]
+        from_buf = tobytes(writable_buf)[:len(test_string)+10]
         self.assertEqual(from_buf, test_string[:10] + test_string)
 
         # Go beyond boundaries.
-        small_buf = array.array('c', ' '*10)
+        small_buf = cls(' '*10)
         self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
                           test_string)
         self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
@@ -461,6 +461,15 @@ class StructTest(unittest.TestCase):
         self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
                           None)
 
+    def test_pack_into_array(self):
+        self.test_pack_into(cls=lambda b: array.array('c', b),
+                            tobytes=array.array.tostring)
+
+    def test_pack_into_memoryview(self):
+        # Issue #22113
+        self.test_pack_into(cls=lambda b: memoryview(bytearray(b)),
+                            tobytes=memoryview.tobytes)
+
     def test_pack_into_fn(self):
         test_string = 'Reykjavik rocks, eow!'
         writable_buf = array.array('c', ' '*100)
index 46cbab5..8fe8995 100644 (file)
@@ -71,7 +71,6 @@ class TestUntestedModules(unittest.TestCase):
             import sunaudio
             import symbol
             import tabnanny
-            import timeit
             import toaiff
             import token
             try:
index 7b83190..75563cb 100644 (file)
@@ -28,7 +28,8 @@ except ImportError:
 __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
            "verbose", "use_resources", "max_memuse", "record_original_stdout",
            "get_original_stdout", "unload", "unlink", "rmtree", "forget",
-           "is_resource_enabled", "requires", "find_unused_port", "bind_port",
+           "is_resource_enabled", "requires", "requires_mac_ver",
+           "find_unused_port", "bind_port",
            "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
            "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error",
            "open_urlresource", "check_warnings", "check_py3k_warnings",
@@ -36,7 +37,7 @@ __all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
            "captured_stdout", "TransientResource", "transient_internet",
            "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
            "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
-           "threading_cleanup", "reap_children", "cpython_only",
+           "threading_cleanup", "reap_threads", "start_threads", "cpython_only",
            "check_impl_detail", "get_attribute", "py3k_bytes",
            "import_fresh_module", "threading_cleanup", "reap_children",
            "strip_python_stderr", "IPV6_ENABLED"]
@@ -361,6 +362,33 @@ def requires(resource, msg=None):
             msg = "Use of the `%s' resource not enabled" % resource
         raise ResourceDenied(msg)
 
+def requires_mac_ver(*min_version):
+    """Decorator raising SkipTest if the OS is Mac OS X and the OS X
+    version if less than min_version.
+
+    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
+    is lesser than 10.5.
+    """
+    def decorator(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kw):
+            if sys.platform == 'darwin':
+                version_txt = platform.mac_ver()[0]
+                try:
+                    version = tuple(map(int, version_txt.split('.')))
+                except ValueError:
+                    pass
+                else:
+                    if version < min_version:
+                        min_version_txt = '.'.join(map(str, min_version))
+                        raise unittest.SkipTest(
+                            "Mac OS X %s or higher required, not %s"
+                            % (min_version_txt, version_txt))
+            return func(*args, **kw)
+        wrapper.min_version = min_version
+        return wrapper
+    return decorator
+
 
 # Don't use "localhost", since resolving it uses the DNS under recent
 # Windows versions (see issue #18792).
@@ -1481,6 +1509,39 @@ def reap_children():
                 break
 
 @contextlib.contextmanager
+def start_threads(threads, unlock=None):
+    threads = list(threads)
+    started = []
+    try:
+        try:
+            for t in threads:
+                t.start()
+                started.append(t)
+        except:
+            if verbose:
+                print("Can't start %d threads, only %d threads started" %
+                      (len(threads), len(started)))
+            raise
+        yield
+    finally:
+        if unlock:
+            unlock()
+        endtime = starttime = time.time()
+        for timeout in range(1, 16):
+            endtime += 60
+            for t in started:
+                t.join(max(endtime - time.time(), 0.01))
+            started = [t for t in started if t.isAlive()]
+            if not started:
+                break
+            if verbose:
+                print('Unable to join %d threads during a period of '
+                      '%d minutes' % (len(started), timeout))
+    started = [t for t in started if t.isAlive()]
+    if started:
+        raise AssertionError('Unable to join %d threads' % len(started))
+
+@contextlib.contextmanager
 def swap_attr(obj, attr, new_val):
     """Temporary swap out an attribute with a new object.
 
index 1e1bdbe..ab35ba4 100644 (file)
@@ -425,6 +425,7 @@ class SysModuleTest(unittest.TestCase):
             self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
         self.assertTrue(repr(sys.flags))
 
+    @test.test_support.cpython_only
     def test_clear_type_cache(self):
         sys._clear_type_cache()
 
index 9c7bcef..1eea786 100644 (file)
@@ -551,6 +551,15 @@ def jump_in_nested_finally(output):
 jump_in_nested_finally.jump = (4, 9)
 jump_in_nested_finally.output = [2, 9]
 
+def jump_infinite_while_loop(output):
+    output.append(1)
+    while 1:
+        output.append(2)
+    output.append(3)
+
+jump_infinite_while_loop.jump = (3, 4)
+jump_infinite_while_loop.output = [1, 3]
+
 # The second set of 'jump' tests are for things that are not allowed:
 
 def no_jump_too_far_forwards(output):
@@ -723,6 +732,8 @@ class JumpTestCase(unittest.TestCase):
         self.run_test(jump_to_same_line)
     def test_07_jump_in_nested_finally(self):
         self.run_test(jump_in_nested_finally)
+    def test_jump_infinite_while_loop(self):
+        self.run_test(jump_infinite_while_loop)
     def test_08_no_jump_too_far_forwards(self):
         self.run_test(no_jump_too_far_forwards)
     def test_09_no_jump_too_far_backwards(self):
index 5836989..9c9afde 100644 (file)
@@ -1,4 +1,5 @@
 import unittest
+import re
 import sys
 import os
 from test import test_support
@@ -18,27 +19,22 @@ try:
 except ImportError:
     INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
 
-tcl_version = _tkinter.TCL_VERSION.split('.')
-try:
-    for i in range(len(tcl_version)):
-        tcl_version[i] = int(tcl_version[i])
-except ValueError:
-    pass
-tcl_version = tuple(tcl_version)
+tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.')))
 
 _tk_patchlevel = None
 def get_tk_patchlevel():
     global _tk_patchlevel
     if _tk_patchlevel is None:
         tcl = Tcl()
-        patchlevel = []
-        for x in tcl.call('info', 'patchlevel').split('.'):
-            try:
-                x = int(x, 10)
-            except ValueError:
-                x = -1
-            patchlevel.append(x)
-        _tk_patchlevel = tuple(patchlevel)
+        patchlevel = tcl.call('info', 'patchlevel')
+        m = re.match(r'(\d+)\.(\d+)([ab.])(\d+)$', patchlevel)
+        major, minor, releaselevel, serial = m.groups()
+        major, minor, serial = int(major), int(minor), int(serial)
+        releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
+        if releaselevel == 'final':
+            _tk_patchlevel = major, minor, serial, releaselevel, 0
+        else:
+            _tk_patchlevel = major, minor, 0, releaselevel, serial
     return _tk_patchlevel
 
 
@@ -130,9 +126,28 @@ class TclTest(unittest.TestCase):
         tcl = self.interp
         self.assertRaises(TclError,tcl.unsetvar,'a')
 
+    def get_integers(self):
+        integers = (0, 1, -1, 2**31-1, -2**31)
+        if tcl_version >= (8, 4):  # wideInt was added in Tcl 8.4
+            integers += (2**31, -2**31-1, 2**63-1, -2**63)
+        # bignum was added in Tcl 8.5, but its support is able only since 8.5.8
+        if (get_tk_patchlevel() >= (8, 6, 0, 'final') or
+            (8, 5, 8) <= get_tk_patchlevel() < (8, 6)):
+            integers += (2**63, -2**63-1, 2**1000, -2**1000)
+        return integers
+
     def test_getint(self):
         tcl = self.interp.tk
-        self.assertEqual(tcl.getint(' 42 '), 42)
+        for i in self.get_integers():
+            result = tcl.getint(' %d ' % i)
+            self.assertEqual(result, i)
+            self.assertIsInstance(result, type(int(result)))
+            if tcl_version >= (8, 5):
+                self.assertEqual(tcl.getint(' {:#o} '.format(i)), i)
+            self.assertEqual(tcl.getint(' %#o ' % i), i)
+            self.assertEqual(tcl.getint(' %#x ' % i), i)
+        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
+            self.assertRaises(TclError, tcl.getint, str(2**1000))
         self.assertEqual(tcl.getint(42), 42)
         self.assertRaises(TypeError, tcl.getint)
         self.assertRaises(TypeError, tcl.getint, '42', '10')
@@ -165,7 +180,12 @@ class TclTest(unittest.TestCase):
         tcl = self.interp.tk
         self.assertIs(tcl.getboolean('on'), True)
         self.assertIs(tcl.getboolean('1'), True)
-        self.assertEqual(tcl.getboolean(42), 42)
+        self.assertIs(tcl.getboolean(u'on'), True)
+        self.assertIs(tcl.getboolean(u'1'), True)
+        self.assertIs(tcl.getboolean(42), True)
+        self.assertIs(tcl.getboolean(0), False)
+        self.assertIs(tcl.getboolean(42L), True)
+        self.assertIs(tcl.getboolean(0L), False)
         self.assertRaises(TypeError, tcl.getboolean)
         self.assertRaises(TypeError, tcl.getboolean, 'on', '1')
         self.assertRaises(TypeError, tcl.getboolean, 1.0)
@@ -286,7 +306,7 @@ class TclTest(unittest.TestCase):
         check('"a\xc2\xbd\xe2\x82\xac"', 'a\xc2\xbd\xe2\x82\xac')
         check(r'"a\xbd\u20ac"', 'a\xc2\xbd\xe2\x82\xac')
         check(r'"a\0b"', 'a\xc0\x80b')
-        if tcl_version >= (8, 5):
+        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
             check('2**64', str(2**64))
 
     def test_exprdouble(self):
@@ -317,7 +337,7 @@ class TclTest(unittest.TestCase):
         check('[string length "a\xc2\xbd\xe2\x82\xac"]', 3.0)
         check(r'[string length "a\xbd\u20ac"]', 3.0)
         self.assertRaises(TclError, tcl.exprdouble, '"abc"')
-        if tcl_version >= (8, 5):
+        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
             check('2**64', float(2**64))
 
     def test_exprlong(self):
@@ -348,7 +368,7 @@ class TclTest(unittest.TestCase):
         check('[string length "a\xc2\xbd\xe2\x82\xac"]', 3)
         check(r'[string length "a\xbd\u20ac"]', 3)
         self.assertRaises(TclError, tcl.exprlong, '"abc"')
-        if tcl_version >= (8, 5):
+        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
             self.assertRaises(TclError, tcl.exprlong, '2**64')
 
     def test_exprboolean(self):
@@ -388,9 +408,44 @@ class TclTest(unittest.TestCase):
         check('[string length "a\xc2\xbd\xe2\x82\xac"]', True)
         check(r'[string length "a\xbd\u20ac"]', True)
         self.assertRaises(TclError, tcl.exprboolean, '"abc"')
-        if tcl_version >= (8, 5):
+        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
             check('2**64', True)
 
+    @unittest.skipUnless(tcl_version >= (8, 5), 'requires Tcl version >= 8.5')
+    def test_booleans(self):
+        tcl = self.interp
+        def check(expr, expected):
+            result = tcl.call('expr', expr)
+            if tcl.wantobjects():
+                self.assertEqual(result, expected)
+                self.assertIsInstance(result, int)
+            else:
+                self.assertIn(result, (expr, str(int(expected))))
+                self.assertIsInstance(result, str)
+        check('true', True)
+        check('yes', True)
+        check('on', True)
+        check('false', False)
+        check('no', False)
+        check('off', False)
+        check('1 < 2', True)
+        check('1 > 2', False)
+
+    def test_expr_bignum(self):
+        tcl = self.interp
+        for i in self.get_integers():
+            result = tcl.call('expr', str(i))
+            if self.wantobjects:
+                self.assertEqual(result, i)
+                self.assertIsInstance(result, (int, long))
+                if abs(result) < 2**31:
+                    self.assertIsInstance(result, int)
+            else:
+                self.assertEqual(result, str(i))
+                self.assertIsInstance(result, str)
+        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
+            self.assertRaises(TclError, tcl.call, 'expr', str(2**1000))
+
     def test_passing_values(self):
         def passValue(value):
             return self.interp.call('set', '_', value)
@@ -408,8 +463,10 @@ class TclTest(unittest.TestCase):
         self.assertEqual(passValue(u'str\x00ing'), u'str\x00ing')
         self.assertEqual(passValue(u'str\x00ing\xbd'), u'str\x00ing\xbd')
         self.assertEqual(passValue(u'str\x00ing\u20ac'), u'str\x00ing\u20ac')
-        for i in (0, 1, -1, int(2**31-1), int(-2**31)):
+        for i in self.get_integers():
             self.assertEqual(passValue(i), i if self.wantobjects else str(i))
+        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
+            self.assertEqual(passValue(2**1000), str(2**1000))
         for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                   sys.float_info.min, sys.float_info.max,
                   -sys.float_info.min, -sys.float_info.max):
@@ -465,8 +522,10 @@ class TclTest(unittest.TestCase):
         check(u'str\x00ing')
         check(u'str\x00ing\xbd')
         check(u'str\x00ing\u20ac')
-        for i in (0, 1, -1, 2**31-1, -2**31):
+        for i in self.get_integers():
             check(i, str(i))
+        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
+            check(2**1000, str(2**1000))
         for f in (0.0, 1.0, -1.0):
             check(f, repr(f))
         for f in (1/3.0, sys.float_info.min, sys.float_info.max,
index 81d9687..c2c30de 100644 (file)
@@ -18,7 +18,7 @@ FILES_PER_THREAD = 50
 
 import tempfile
 
-from test.test_support import threading_setup, threading_cleanup, run_unittest, import_module
+from test.test_support import start_threads, run_unittest, import_module
 threading = import_module('threading')
 import unittest
 import StringIO
@@ -46,25 +46,12 @@ class TempFileGreedy(threading.Thread):
 
 class ThreadedTempFileTest(unittest.TestCase):
     def test_main(self):
-        threads = []
-        thread_info = threading_setup()
-
-        for i in range(NUM_THREADS):
-            t = TempFileGreedy()
-            threads.append(t)
-            t.start()
-
-        startEvent.set()
-
-        ok = 0
-        errors = []
-        for t in threads:
-            t.join()
-            ok += t.ok_count
-            if t.error_count:
-                errors.append(str(t.getName()) + str(t.errors.getvalue()))
-
-        threading_cleanup(*thread_info)
+        threads = [TempFileGreedy() for i in range(NUM_THREADS)]
+        with start_threads(threads, startEvent.set):
+            pass
+        ok = sum(t.ok_count for t in threads)
+        errors = [str(t.getName()) + str(t.errors.getvalue())
+                  for t in threads if t.error_count]
 
         msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
             '\n'.join(errors))
index 00b8d19..44f2c57 100644 (file)
@@ -797,7 +797,7 @@ class ThreadingExceptionTests(BaseTestCase):
                 running = True
                 while running:
                     time.sleep(0.01)
-                1/0
+                1.0/0.0
             t = threading.Thread(target=run)
             t.start()
             while not running:
@@ -824,7 +824,7 @@ class ThreadingExceptionTests(BaseTestCase):
                 running = True
                 while running:
                     time.sleep(0.01)
-                1/0
+                1.0/0.0
             t = threading.Thread(target=run)
             t.start()
             while not running:
@@ -852,7 +852,7 @@ class ThreadingExceptionTests(BaseTestCase):
                 running = True
                 while running:
                     time.sleep(0.01)
-                1/0
+                1.0/0.0
             sys.stderr = None
             t = threading.Thread(target=run)
             t.start()
index 4c9f296..b161315 100644 (file)
@@ -1,12 +1,12 @@
 import unittest
 from doctest import DocTestSuite
-from test import test_support
+from test import test_support as support
 import weakref
 import gc
 
 # Modules under test
-_thread = test_support.import_module('thread')
-threading = test_support.import_module('threading')
+_thread = support.import_module('thread')
+threading = support.import_module('threading')
 import _threading_local
 
 
@@ -63,14 +63,9 @@ class BaseLocalTest:
             # Simply check that the variable is correctly set
             self.assertEqual(local.x, i)
 
-        threads= []
-        for i in range(10):
-            t = threading.Thread(target=f, args=(i,))
-            t.start()
-            threads.append(t)
-
-        for t in threads:
-            t.join()
+        with support.start_threads(threading.Thread(target=f, args=(i,))
+                                   for i in range(10)):
+            pass
 
     def test_derived_cycle_dealloc(self):
         # http://bugs.python.org/issue6990
@@ -228,7 +223,7 @@ def test_main():
                                    setUp=setUp, tearDown=tearDown)
                       )
 
-    test_support.run_unittest(suite)
+    support.run_unittest(suite)
 
 if __name__ == '__main__':
     test_main()
diff --git a/Lib/test/test_timeit.py b/Lib/test/test_timeit.py
new file mode 100644 (file)
index 0000000..a084b68
--- /dev/null
@@ -0,0 +1,312 @@
+import timeit
+import unittest
+import sys
+from StringIO import StringIO
+import time
+from textwrap import dedent
+
+from test.test_support import run_unittest
+from test.test_support import captured_stdout
+from test.test_support import captured_stderr
+
+# timeit's default number of iterations.
+DEFAULT_NUMBER = 1000000
+
+# timeit's default number of repetitions.
+DEFAULT_REPEAT = 3
+
+# XXX: some tests are commented out that would improve the coverage but take a
+# long time to run because they test the default number of loops, which is
+# large.  The tests could be enabled if there was a way to override the default
+# number of loops during testing, but this would require changing the signature
+# of some functions that use the default as a default argument.
+
+class FakeTimer:
+    BASE_TIME = 42.0
+    def __init__(self, seconds_per_increment=1.0):
+        self.count = 0
+        self.setup_calls = 0
+        self.seconds_per_increment=seconds_per_increment
+        timeit._fake_timer = self
+
+    def __call__(self):
+        return self.BASE_TIME + self.count * self.seconds_per_increment
+
+    def inc(self):
+        self.count += 1
+
+    def setup(self):
+        self.setup_calls += 1
+
+    def wrap_timer(self, timer):
+        """Records 'timer' and returns self as callable timer."""
+        self.saved_timer = timer
+        return self
+
+class TestTimeit(unittest.TestCase):
+
+    def tearDown(self):
+        try:
+            del timeit._fake_timer
+        except AttributeError:
+            pass
+
+    def test_reindent_empty(self):
+        self.assertEqual(timeit.reindent("", 0), "")
+        self.assertEqual(timeit.reindent("", 4), "")
+
+    def test_reindent_single(self):
+        self.assertEqual(timeit.reindent("pass", 0), "pass")
+        self.assertEqual(timeit.reindent("pass", 4), "pass")
+
+    def test_reindent_multi_empty(self):
+        self.assertEqual(timeit.reindent("\n\n", 0), "\n\n")
+        self.assertEqual(timeit.reindent("\n\n", 4), "\n    \n    ")
+
+    def test_reindent_multi(self):
+        self.assertEqual(timeit.reindent(
+            "print()\npass\nbreak", 0),
+            "print()\npass\nbreak")
+        self.assertEqual(timeit.reindent(
+            "print()\npass\nbreak", 4),
+            "print()\n    pass\n    break")
+
+    def test_timer_invalid_stmt(self):
+        self.assertRaises(ValueError, timeit.Timer, stmt=None)
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='return')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='yield')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='break')
+        self.assertRaises(SyntaxError, timeit.Timer, stmt='continue')
+
+    def test_timer_invalid_setup(self):
+        self.assertRaises(ValueError, timeit.Timer, setup=None)
+        self.assertRaises(SyntaxError, timeit.Timer, setup='return')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='yield')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='break')
+        self.assertRaises(SyntaxError, timeit.Timer, setup='continue')
+
+    fake_setup = "import timeit; timeit._fake_timer.setup()"
+    fake_stmt = "import timeit; timeit._fake_timer.inc()"
+
+    def fake_callable_setup(self):
+        self.fake_timer.setup()
+
+    def fake_callable_stmt(self):
+        self.fake_timer.inc()
+
+    def timeit(self, stmt, setup, number=None):
+        self.fake_timer = FakeTimer()
+        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
+        kwargs = {}
+        if number is None:
+            number = DEFAULT_NUMBER
+        else:
+            kwargs['number'] = number
+        delta_time = t.timeit(**kwargs)
+        self.assertEqual(self.fake_timer.setup_calls, 1)
+        self.assertEqual(self.fake_timer.count, number)
+        self.assertEqual(delta_time, number)
+
+    # Takes too long to run in debug build.
+    #def test_timeit_default_iters(self):
+    #    self.timeit(self.fake_stmt, self.fake_setup)
+
+    def test_timeit_zero_iters(self):
+        self.timeit(self.fake_stmt, self.fake_setup, number=0)
+
+    def test_timeit_few_iters(self):
+        self.timeit(self.fake_stmt, self.fake_setup, number=3)
+
+    def test_timeit_callable_stmt(self):
+        self.timeit(self.fake_callable_stmt, self.fake_setup, number=3)
+
+    def test_timeit_callable_stmt_and_setup(self):
+        self.timeit(self.fake_callable_stmt,
+                self.fake_callable_setup, number=3)
+
+    # Takes too long to run in debug build.
+    #def test_timeit_function(self):
+    #    delta_time = timeit.timeit(self.fake_stmt, self.fake_setup,
+    #            timer=FakeTimer())
+    #    self.assertEqual(delta_time, DEFAULT_NUMBER)
+
+    def test_timeit_function_zero_iters(self):
+        delta_time = timeit.timeit(self.fake_stmt, self.fake_setup, number=0,
+                timer=FakeTimer())
+        self.assertEqual(delta_time, 0)
+
+    def repeat(self, stmt, setup, repeat=None, number=None):
+        self.fake_timer = FakeTimer()
+        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
+        kwargs = {}
+        if repeat is None:
+            repeat = DEFAULT_REPEAT
+        else:
+            kwargs['repeat'] = repeat
+        if number is None:
+            number = DEFAULT_NUMBER
+        else:
+            kwargs['number'] = number
+        delta_times = t.repeat(**kwargs)
+        self.assertEqual(self.fake_timer.setup_calls, repeat)
+        self.assertEqual(self.fake_timer.count, repeat * number)
+        self.assertEqual(delta_times, repeat * [float(number)])
+
+    # Takes too long to run in debug build.
+    #def test_repeat_default(self):
+    #    self.repeat(self.fake_stmt, self.fake_setup)
+
+    def test_repeat_zero_reps(self):
+        self.repeat(self.fake_stmt, self.fake_setup, repeat=0)
+
+    def test_repeat_zero_iters(self):
+        self.repeat(self.fake_stmt, self.fake_setup, number=0)
+
+    def test_repeat_few_reps_and_iters(self):
+        self.repeat(self.fake_stmt, self.fake_setup, repeat=3, number=5)
+
+    def test_repeat_callable_stmt(self):
+        self.repeat(self.fake_callable_stmt, self.fake_setup,
+                repeat=3, number=5)
+
+    def test_repeat_callable_stmt_and_setup(self):
+        self.repeat(self.fake_callable_stmt, self.fake_callable_setup,
+                repeat=3, number=5)
+
+    # Takes too long to run in debug build.
+    #def test_repeat_function(self):
+    #    delta_times = timeit.repeat(self.fake_stmt, self.fake_setup,
+    #            timer=FakeTimer())
+    #    self.assertEqual(delta_times, DEFAULT_REPEAT * [float(DEFAULT_NUMBER)])
+
+    def test_repeat_function_zero_reps(self):
+        delta_times = timeit.repeat(self.fake_stmt, self.fake_setup, repeat=0,
+                timer=FakeTimer())
+        self.assertEqual(delta_times, [])
+
+    def test_repeat_function_zero_iters(self):
+        delta_times = timeit.repeat(self.fake_stmt, self.fake_setup, number=0,
+                timer=FakeTimer())
+        self.assertEqual(delta_times, DEFAULT_REPEAT * [0.0])
+
+    def assert_exc_string(self, exc_string, expected_exc_name):
+        exc_lines = exc_string.splitlines()
+        self.assertGreater(len(exc_lines), 2)
+        self.assertTrue(exc_lines[0].startswith('Traceback'))
+        self.assertTrue(exc_lines[-1].startswith(expected_exc_name))
+
+    def test_print_exc(self):
+        s = StringIO()
+        t = timeit.Timer("1.0/0.0")
+        try:
+            t.timeit()
+        except:
+            t.print_exc(s)
+        self.assert_exc_string(s.getvalue(), 'ZeroDivisionError')
+
+    MAIN_DEFAULT_OUTPUT = "10 loops, best of 3: 1 sec per loop\n"
+
+    def run_main(self, seconds_per_increment=1.0, switches=None, timer=None):
+        if timer is None:
+            timer = FakeTimer(seconds_per_increment=seconds_per_increment)
+        if switches is None:
+            args = []
+        else:
+            args = switches[:]
+        args.append(self.fake_stmt)
+        # timeit.main() modifies sys.path, so save and restore it.
+        orig_sys_path = sys.path[:]
+        with captured_stdout() as s:
+            timeit.main(args=args, _wrap_timer=timer.wrap_timer)
+        sys.path[:] = orig_sys_path[:]
+        return s.getvalue()
+
+    def test_main_bad_switch(self):
+        s = self.run_main(switches=['--bad-switch'])
+        self.assertEqual(s, dedent("""\
+            option --bad-switch not recognized
+            use -h/--help for command line help
+            """))
+
+    def test_main_seconds(self):
+        s = self.run_main(seconds_per_increment=5.5)
+        self.assertEqual(s, "10 loops, best of 3: 5.5 sec per loop\n")
+
+    def test_main_milliseconds(self):
+        s = self.run_main(seconds_per_increment=0.0055)
+        self.assertEqual(s, "100 loops, best of 3: 5.5 msec per loop\n")
+
+    def test_main_microseconds(self):
+        s = self.run_main(seconds_per_increment=0.0000025, switches=['-n100'])
+        self.assertEqual(s, "100 loops, best of 3: 2.5 usec per loop\n")
+
+    def test_main_fixed_iters(self):
+        s = self.run_main(seconds_per_increment=2.0, switches=['-n35'])
+        self.assertEqual(s, "35 loops, best of 3: 2 sec per loop\n")
+
+    def test_main_setup(self):
+        s = self.run_main(seconds_per_increment=2.0,
+                switches=['-n35', '-s', 'print("CustomSetup")'])
+        self.assertEqual(s, "CustomSetup\n" * 3 +
+                "35 loops, best of 3: 2 sec per loop\n")
+
+    def test_main_fixed_reps(self):
+        s = self.run_main(seconds_per_increment=60.0, switches=['-r9'])
+        self.assertEqual(s, "10 loops, best of 9: 60 sec per loop\n")
+
+    def test_main_negative_reps(self):
+        s = self.run_main(seconds_per_increment=60.0, switches=['-r-5'])
+        self.assertEqual(s, "10 loops, best of 1: 60 sec per loop\n")
+
+    @unittest.skipIf(sys.flags.optimize >= 2, "need __doc__")
+    def test_main_help(self):
+        s = self.run_main(switches=['-h'])
+        self.assertEqual(s, timeit.__doc__)
+
+    def test_main_using_time(self):
+        fake_timer = FakeTimer()
+        s = self.run_main(switches=['-t'], timer=fake_timer)
+        self.assertEqual(s, self.MAIN_DEFAULT_OUTPUT)
+        self.assertIs(fake_timer.saved_timer, time.time)
+
+    def test_main_using_clock(self):
+        fake_timer = FakeTimer()
+        s = self.run_main(switches=['-c'], timer=fake_timer)
+        self.assertEqual(s, self.MAIN_DEFAULT_OUTPUT)
+        self.assertIs(fake_timer.saved_timer, time.clock)
+
+    def test_main_verbose(self):
+        s = self.run_main(switches=['-v'])
+        self.assertEqual(s, dedent("""\
+                10 loops -> 10 secs
+                raw times: 10 10 10
+                10 loops, best of 3: 1 sec per loop
+            """))
+
+    def test_main_very_verbose(self):
+        s = self.run_main(seconds_per_increment=0.000050, switches=['-vv'])
+        self.assertEqual(s, dedent("""\
+                10 loops -> 0.0005 secs
+                100 loops -> 0.005 secs
+                1000 loops -> 0.05 secs
+                10000 loops -> 0.5 secs
+                raw times: 0.5 0.5 0.5
+                10000 loops, best of 3: 50 usec per loop
+            """))
+
+    def test_main_exception(self):
+        with captured_stderr() as error_stringio:
+            s = self.run_main(switches=['1.0/0.0'])
+        self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
+
+    def test_main_exception_fixed_reps(self):
+        with captured_stderr() as error_stringio:
+            s = self.run_main(switches=['-n1', '1.0/0.0'])
+        self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError')
+
+
+def test_main():
+    run_unittest(TestTimeit)
+
+if __name__ == '__main__':
+    test_main()
index 9f6cc75..625d08c 100644 (file)
@@ -874,9 +874,9 @@ class UnicodeTest(
     def test_utf8_decode_invalid_sequences(self):
         # continuation bytes in a sequence of 2, 3, or 4 bytes
         continuation_bytes = map(chr, range(0x80, 0xC0))
-        # start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
+        # start bytes of a 2-byte sequence equivalent to code points < 0x7F
         invalid_2B_seq_start_bytes = map(chr, range(0xC0, 0xC2))
-        # start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
+        # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
         invalid_4B_seq_start_bytes = map(chr, range(0xF5, 0xF8))
         invalid_start_bytes = (
             continuation_bytes + invalid_2B_seq_start_bytes +
@@ -1700,6 +1700,9 @@ class UnicodeTest(
         if sys.maxunicode > 0xffff:
             check_format(u'\U0010ffff',
                          b'%c', c_int(0x10ffff))
+        else:
+            with self.assertRaises(OverflowError):
+                PyUnicode_FromFormat(b'%c', c_int(0x10000))
         with self.assertRaises(OverflowError):
             PyUnicode_FromFormat(b'%c', c_int(0x110000))
         # Issue #18183
@@ -1750,8 +1753,45 @@ class UnicodeTest(
                      b'%zu', c_size_t(123))
 
         # test long output
+        min_long = -(2 ** (8 * sizeof(c_long) - 1))
+        max_long = -min_long - 1
+        check_format(unicode(min_long),
+                     b'%ld', c_long(min_long))
+        check_format(unicode(max_long),
+                     b'%ld', c_long(max_long))
+        max_ulong = 2 ** (8 * sizeof(c_ulong)) - 1
+        check_format(unicode(max_ulong),
+                     b'%lu', c_ulong(max_ulong))
         PyUnicode_FromFormat(b'%p', c_void_p(-1))
 
+        # test padding (width and/or precision)
+        check_format(u'123'.rjust(10, u'0'),
+                     b'%010i', c_int(123))
+        check_format(u'123'.rjust(100),
+                     b'%100i', c_int(123))
+        check_format(u'123'.rjust(100, u'0'),
+                     b'%.100i', c_int(123))
+        check_format(u'123'.rjust(80, u'0').rjust(100),
+                     b'%100.80i', c_int(123))
+
+        check_format(u'123'.rjust(10, u'0'),
+                     b'%010u', c_uint(123))
+        check_format(u'123'.rjust(100),
+                     b'%100u', c_uint(123))
+        check_format(u'123'.rjust(100, u'0'),
+                     b'%.100u', c_uint(123))
+        check_format(u'123'.rjust(80, u'0').rjust(100),
+                     b'%100.80u', c_uint(123))
+
+        check_format(u'123'.rjust(10, u'0'),
+                     b'%010x', c_int(0x123))
+        check_format(u'123'.rjust(100),
+                     b'%100x', c_int(0x123))
+        check_format(u'123'.rjust(100, u'0'),
+                     b'%.100x', c_int(0x123))
+        check_format(u'123'.rjust(80, u'0').rjust(100),
+                     b'%100.80x', c_int(0x123))
+
         # test %V
         check_format(u'repr=abc',
                      b'repr=%V', u'abc', b'xyz')
index 0032865..adffb57 100644 (file)
@@ -773,21 +773,55 @@ class Pathname_Tests(unittest.TestCase):
 
 class Utility_Tests(unittest.TestCase):
     """Testcase to test the various utility functions in the urllib."""
+    # In Python 3 this test class is moved to test_urlparse.
+
+    def test_splittype(self):
+        splittype = urllib.splittype
+        self.assertEqual(splittype('type:opaquestring'), ('type', 'opaquestring'))
+        self.assertEqual(splittype('opaquestring'), (None, 'opaquestring'))
+        self.assertEqual(splittype(':opaquestring'), (None, ':opaquestring'))
+        self.assertEqual(splittype('type:'), ('type', ''))
+        self.assertEqual(splittype('type:opaque:string'), ('type', 'opaque:string'))
+
+    def test_splithost(self):
+        splithost = urllib.splithost
+        self.assertEqual(splithost('//www.example.org:80/foo/bar/baz.html'),
+                         ('www.example.org:80', '/foo/bar/baz.html'))
+        self.assertEqual(splithost('//www.example.org:80'),
+                         ('www.example.org:80', ''))
+        self.assertEqual(splithost('/foo/bar/baz.html'),
+                         (None, '/foo/bar/baz.html'))
+
+    def test_splituser(self):
+        splituser = urllib.splituser
+        self.assertEqual(splituser('User:Pass@www.python.org:080'),
+                         ('User:Pass', 'www.python.org:080'))
+        self.assertEqual(splituser('@www.python.org:080'),
+                         ('', 'www.python.org:080'))
+        self.assertEqual(splituser('www.python.org:080'),
+                         (None, 'www.python.org:080'))
+        self.assertEqual(splituser('User:Pass@'),
+                         ('User:Pass', ''))
+        self.assertEqual(splituser('User@example.com:Pass@www.python.org:080'),
+                         ('User@example.com:Pass', 'www.python.org:080'))
 
     def test_splitpasswd(self):
-        """Some of the password examples are not sensible, but it is added to
-        confirming to RFC2617 and addressing issue4675.
-        """
-        self.assertEqual(('user', 'ab'),urllib.splitpasswd('user:ab'))
-        self.assertEqual(('user', 'a\nb'),urllib.splitpasswd('user:a\nb'))
-        self.assertEqual(('user', 'a\tb'),urllib.splitpasswd('user:a\tb'))
-        self.assertEqual(('user', 'a\rb'),urllib.splitpasswd('user:a\rb'))
-        self.assertEqual(('user', 'a\fb'),urllib.splitpasswd('user:a\fb'))
-        self.assertEqual(('user', 'a\vb'),urllib.splitpasswd('user:a\vb'))
-        self.assertEqual(('user', 'a:b'),urllib.splitpasswd('user:a:b'))
-        self.assertEqual(('user', 'a b'),urllib.splitpasswd('user:a b'))
-        self.assertEqual(('user 2', 'ab'),urllib.splitpasswd('user 2:ab'))
-        self.assertEqual(('user+1', 'a+b'),urllib.splitpasswd('user+1:a+b'))
+        # Some of the password examples are not sensible, but it is added to
+        # confirming to RFC2617 and addressing issue4675.
+        splitpasswd = urllib.splitpasswd
+        self.assertEqual(splitpasswd('user:ab'), ('user', 'ab'))
+        self.assertEqual(splitpasswd('user:a\nb'), ('user', 'a\nb'))
+        self.assertEqual(splitpasswd('user:a\tb'), ('user', 'a\tb'))
+        self.assertEqual(splitpasswd('user:a\rb'), ('user', 'a\rb'))
+        self.assertEqual(splitpasswd('user:a\fb'), ('user', 'a\fb'))
+        self.assertEqual(splitpasswd('user:a\vb'), ('user', 'a\vb'))
+        self.assertEqual(splitpasswd('user:a:b'), ('user', 'a:b'))
+        self.assertEqual(splitpasswd('user:a b'), ('user', 'a b'))
+        self.assertEqual(splitpasswd('user 2:ab'), ('user 2', 'ab'))
+        self.assertEqual(splitpasswd('user+1:a+b'), ('user+1', 'a+b'))
+        self.assertEqual(splitpasswd('user:'), ('user', ''))
+        self.assertEqual(splitpasswd('user'), ('user', None))
+        self.assertEqual(splitpasswd(':ab'), ('', 'ab'))
 
     def test_splitport(self):
         splitport = urllib.splitport
@@ -796,6 +830,9 @@ class Utility_Tests(unittest.TestCase):
         self.assertEqual(splitport('parrot:'), ('parrot', None))
         self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None))
         self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None))
+        self.assertEqual(splitport('[::1]:88'), ('[::1]', '88'))
+        self.assertEqual(splitport('[::1]'), ('[::1]', None))
+        self.assertEqual(splitport(':88'), ('', '88'))
 
     def test_splitnport(self):
         splitnport = urllib.splitnport
@@ -809,6 +846,59 @@ class Utility_Tests(unittest.TestCase):
         self.assertEqual(splitnport('parrot:cheese'), ('parrot', None))
         self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None))
 
+    def test_splitquery(self):
+        # Normal cases are exercised by other tests; ensure that we also
+        # catch cases with no port specified (testcase ensuring coverage)
+        splitquery = urllib.splitquery
+        self.assertEqual(splitquery('http://python.org/fake?foo=bar'),
+                         ('http://python.org/fake', 'foo=bar'))
+        self.assertEqual(splitquery('http://python.org/fake?foo=bar?'),
+                         ('http://python.org/fake?foo=bar', ''))
+        self.assertEqual(splitquery('http://python.org/fake'),
+                         ('http://python.org/fake', None))
+        self.assertEqual(splitquery('?foo=bar'), ('', 'foo=bar'))
+
+    def test_splittag(self):
+        splittag = urllib.splittag
+        self.assertEqual(splittag('http://example.com?foo=bar#baz'),
+                         ('http://example.com?foo=bar', 'baz'))
+        self.assertEqual(splittag('http://example.com?foo=bar#'),
+                         ('http://example.com?foo=bar', ''))
+        self.assertEqual(splittag('#baz'), ('', 'baz'))
+        self.assertEqual(splittag('http://example.com?foo=bar'),
+                         ('http://example.com?foo=bar', None))
+        self.assertEqual(splittag('http://example.com?foo=bar#baz#boo'),
+                         ('http://example.com?foo=bar#baz', 'boo'))
+
+    def test_splitattr(self):
+        splitattr = urllib.splitattr
+        self.assertEqual(splitattr('/path;attr1=value1;attr2=value2'),
+                         ('/path', ['attr1=value1', 'attr2=value2']))
+        self.assertEqual(splitattr('/path;'), ('/path', ['']))
+        self.assertEqual(splitattr(';attr1=value1;attr2=value2'),
+                         ('', ['attr1=value1', 'attr2=value2']))
+        self.assertEqual(splitattr('/path'), ('/path', []))
+
+    def test_splitvalue(self):
+        # Normal cases are exercised by other tests; test pathological cases
+        # with no key/value pairs. (testcase ensuring coverage)
+        splitvalue = urllib.splitvalue
+        self.assertEqual(splitvalue('foo=bar'), ('foo', 'bar'))
+        self.assertEqual(splitvalue('foo='), ('foo', ''))
+        self.assertEqual(splitvalue('=bar'), ('', 'bar'))
+        self.assertEqual(splitvalue('foobar'), ('foobar', None))
+        self.assertEqual(splitvalue('foo=bar=baz'), ('foo', 'bar=baz'))
+
+    def test_toBytes(self):
+        result = urllib.toBytes(u'http://www.python.org')
+        self.assertEqual(result, 'http://www.python.org')
+        self.assertRaises(UnicodeError, urllib.toBytes,
+                          test_support.u(r'http://www.python.org/medi\u00e6val'))
+
+    def test_unwrap(self):
+        url = urllib.unwrap('<URL:type://host/path>')
+        self.assertEqual(url, 'type://host/path')
+
 
 class URLopener_Tests(unittest.TestCase):
     """Testcase to test the open method of URLopener class."""
index 5b2c708..32ffd0a 100644 (file)
@@ -25,7 +25,7 @@ class TrivialTests(unittest.TestCase):
         self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')
 
         # XXX Name hacking to get this to work on Windows.
-        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')
+        fname = os.path.abspath(urllib2.__file__).replace(os.sep, '/')
 
         # And more hacking to get it to work on MacOS. This assumes
         # urllib.pathname2url works, unfortunately...
index a24a077..bb82b26 100644 (file)
@@ -5,7 +5,6 @@ import urllib2
 import BaseHTTPServer
 import unittest
 import hashlib
-import ssl
 
 from test import test_support
 
@@ -557,7 +556,6 @@ class TestUrlopen(BaseTestCase):
 
     def test_https_with_cafile(self):
         handler = self.start_https_server(certfile=CERT_localhost)
-        import ssl
         # Good cert
         data = self.urlopen("https://localhost:%s/bizarre" % handler.port,
                             cafile=CERT_localhost)
index 818bf53..8eec3ad 100644 (file)
@@ -102,11 +102,9 @@ class OtherNetworkTests(unittest.TestCase):
 
     def test_ftp(self):
         urls = [
-            'ftp://ftp.kernel.org/pub/linux/kernel/README',
-            'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
-            #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
-            'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
-                '/research-reports/00README-Legal-Rules-Regs',
+            'ftp://ftp.debian.org/debian/README',
+            ('ftp://ftp.debian.org/debian/non-existent-file',
+             None, urllib2.URLError),
             ]
         self._test_urls(urls, self._extra_handlers())
 
@@ -284,7 +282,7 @@ class TimeoutTest(unittest.TestCase):
             u = _urlopen_with_retry(url, timeout=120)
             self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
 
-    FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
+    FTP_HOST = 'ftp://ftp.debian.org/debian/'
 
     def test_ftp_basic(self):
         self.assertIsNone(socket.getdefaulttimeout())
index bccfcb7..0a8130e 100644 (file)
@@ -12,9 +12,6 @@ def importable(name):
         return False
 
 class TestUUID(unittest.TestCase):
-    last_node = None
-    source2node = {}
-
     def test_UUID(self):
         equal = self.assertEqual
         ascending = []
@@ -282,119 +279,13 @@ class TestUUID(unittest.TestCase):
         badtype(lambda: setattr(u, 'clock_seq_low', 0))
         badtype(lambda: setattr(u, 'node', 0))
 
-    def check_node(self, node, source):
-        message = "%012x is not an RFC 4122 node ID" % node
-        self.assertTrue(0 < node, message)
-        self.assertTrue(node < (1L << 48), message)
-
-        TestUUID.source2node[source] = node
-        if TestUUID.last_node:
-            if TestUUID.last_node != node:
-                msg = "different sources disagree on node:\n"
-                for s, n in TestUUID.source2node.iteritems():
-                    msg += "    from source %r, node was %012x\n" % (s, n)
-                # There's actually no reason to expect the MAC addresses
-                # to agree across various methods -- e.g., a box may have
-                # multiple network interfaces, and different ways of getting
-                # a MAC address may favor different HW.
-                ##self.fail(msg)
-        else:
-            TestUUID.last_node = node
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    def test_ifconfig_getnode(self):
-        node = uuid._ifconfig_getnode()
-        if node is not None:
-            self.check_node(node, 'ifconfig')
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    def test_arp_getnode(self):
-        node = uuid._arp_getnode()
-        if node is not None:
-            self.check_node(node, 'arp')
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    def test_lanscan_getnode(self):
-        node = uuid._lanscan_getnode()
-        if node is not None:
-            self.check_node(node, 'lanscan')
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    def test_netstat_getnode(self):
-        node = uuid._netstat_getnode()
-        if node is not None:
-            self.check_node(node, 'netstat')
-
-    @unittest.skipUnless(os.name == 'nt', 'requires Windows')
-    def test_ipconfig_getnode(self):
-        node = uuid._ipconfig_getnode()
-        if node is not None:
-            self.check_node(node, 'ipconfig')
-
-    @unittest.skipUnless(importable('win32wnet'), 'requires win32wnet')
-    @unittest.skipUnless(importable('netbios'), 'requires netbios')
-    def test_netbios_getnode(self):
-        self.check_node(uuid._netbios_getnode(), 'netbios')
-
-    def test_random_getnode(self):
-        node = uuid._random_getnode()
-        # Least significant bit of first octet must be set.
-        self.assertTrue(node & 0x010000000000)
-        self.assertTrue(node < (1L << 48))
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    @unittest.skipUnless(importable('ctypes'), 'requires ctypes')
-    def test_unixdll_getnode(self):
-        try: # Issues 1481, 3581: _uuid_generate_time() might be None.
-            self.check_node(uuid._unixdll_getnode(), 'unixdll')
-        except TypeError:
-            pass
-
-    @unittest.skipUnless(os.name == 'nt', 'requires Windows')
-    @unittest.skipUnless(importable('ctypes'), 'requires ctypes')
-    def test_windll_getnode(self):
-        self.check_node(uuid._windll_getnode(), 'windll')
-
     def test_getnode(self):
         node1 = uuid.getnode()
-        self.check_node(node1, "getnode1")
+        self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
 
         # Test it again to ensure consistency.
         node2 = uuid.getnode()
-        self.check_node(node2, "getnode2")
-
-        self.assertEqual(node1, node2)
-
-    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
-    def test_find_mac(self):
-        data = '''\
-
-fake hwaddr
-cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
-eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
-'''
-        def mock_popen(cmd):
-            return io.BytesIO(data)
-
-        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
-        path.extend(('/sbin', '/usr/sbin'))
-        for dir in path:
-            executable = os.path.join(dir, 'ifconfig')
-            if (os.path.exists(executable) and
-                os.access(executable, os.F_OK | os.X_OK) and
-                not os.path.isdir(executable)):
-                break
-        else:
-            self.skipTest('requires ifconfig')
-
-        with test_support.swap_attr(os, 'popen', mock_popen):
-            mac = uuid._find_mac(
-                command='ifconfig',
-                args='',
-                hw_identifiers=['hwaddr'],
-                get_index=lambda x: x + 1,
-            )
-            self.assertEqual(mac, 0x1234567890ab)
+        self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
 
     @unittest.skipUnless(importable('ctypes'), 'requires ctypes')
     def test_uuid1(self):
@@ -506,11 +397,106 @@ eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
             self.assertNotEqual(parent_value, child_value)
 
 
+class TestInternals(unittest.TestCase):
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    def test_find_mac(self):
+        data = '''\
+
+fake hwaddr
+cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
+eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
+'''
+        def mock_popen(cmd):
+            return io.BytesIO(data)
+
+        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
+        path.extend(('/sbin', '/usr/sbin'))
+        for dir in path:
+            executable = os.path.join(dir, 'ifconfig')
+            if (os.path.exists(executable) and
+                os.access(executable, os.F_OK | os.X_OK) and
+                not os.path.isdir(executable)):
+                break
+        else:
+            self.skipTest('requires ifconfig')
+
+        with test_support.swap_attr(os, 'popen', mock_popen):
+            mac = uuid._find_mac(
+                command='ifconfig',
+                args='',
+                hw_identifiers=['hwaddr'],
+                get_index=lambda x: x + 1,
+            )
+            self.assertEqual(mac, 0x1234567890ab)
+
+    def check_node(self, node, requires=None, network=False):
+        if requires and node is None:
+            self.skipTest('requires ' + requires)
+        hex = '%012x' % node
+        if test_support.verbose >= 2:
+            print hex + ' ',
+        if network:
+            # 47 bit will never be set in IEEE 802 addresses obtained
+            # from network cards.
+            self.assertFalse(node & 0x010000000000, hex)
+        self.assertTrue(0 < node < (1L << 48),
+                        "%s is not an RFC 4122 node ID" % hex)
+
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    def test_ifconfig_getnode(self):
+        node = uuid._ifconfig_getnode()
+        self.check_node(node, 'ifconfig', True)
+
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    def test_arp_getnode(self):
+        node = uuid._arp_getnode()
+        self.check_node(node, 'arp', True)
+
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    def test_lanscan_getnode(self):
+        node = uuid._lanscan_getnode()
+        self.check_node(node, 'lanscan', True)
+
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    def test_netstat_getnode(self):
+        node = uuid._netstat_getnode()
+        self.check_node(node, 'netstat', True)
+
+    @unittest.skipUnless(os.name == 'nt', 'requires Windows')
+    def test_ipconfig_getnode(self):
+        node = uuid._ipconfig_getnode()
+        self.check_node(node, 'ipconfig', True)
 
+    @unittest.skipUnless(importable('win32wnet'), 'requires win32wnet')
+    @unittest.skipUnless(importable('netbios'), 'requires netbios')
+    def test_netbios_getnode(self):
+        node = uuid._netbios_getnode()
+        self.check_node(node, network=True)
+
+    def test_random_getnode(self):
+        node = uuid._random_getnode()
+        # Least significant bit of first octet must be set.
+        self.assertTrue(node & 0x010000000000, '%012x' % node)
+        self.check_node(node)
+
+    @unittest.skipUnless(os.name == 'posix', 'requires Posix')
+    @unittest.skipUnless(importable('ctypes'), 'requires ctypes')
+    def test_unixdll_getnode(self):
+        try: # Issues 1481, 3581: _uuid_generate_time() might be None.
+            node = uuid._unixdll_getnode()
+        except TypeError:
+            self.skipTest('requires uuid_generate_time')
+        self.check_node(node)
+
+    @unittest.skipUnless(os.name == 'nt', 'requires Windows')
+    @unittest.skipUnless(importable('ctypes'), 'requires ctypes')
+    def test_windll_getnode(self):
+        node = uuid._windll_getnode()
+        self.check_node(node)
 
 
 def test_main():
-    test_support.run_unittest(TestUUID)
+    test_support.run_unittest(TestUUID, TestInternals)
 
 if __name__ == '__main__':
     test_main()
index fb2046e..7a9459a 100644 (file)
@@ -560,6 +560,15 @@ class _WarningsTests(BaseTest):
         finally:
             globals_dict['__file__'] = oldfile
 
+    def test_stderr_none(self):
+        rc, stdout, stderr = assert_python_ok("-c",
+            "import sys; sys.stderr = None; "
+            "import warnings; warnings.simplefilter('always'); "
+            "warnings.warn('Warning!')")
+        self.assertEqual(stdout, b'')
+        self.assertNotIn(b'Warning!', stderr)
+        self.assertNotIn(b'Error', stderr)
+
 
 class WarningsDisplayTests(unittest.TestCase):
 
index ac3a33f..95ad4eb 100644 (file)
@@ -56,7 +56,7 @@ class DumpPickle_LoadCPickle(AbstractPickleTests):
         # Ignore fast
         return cPickle.loads(buf)
 
-def have_python_version(name):
+def have_python_version(name, cache={}):
     """Check whether the given name is a valid Python binary and has
     test.test_support.
 
@@ -68,7 +68,9 @@ def have_python_version(name):
     Returns:
         True if the name is valid, False otherwise.
     """
-    return os.system(name + " -c 'import test.test_support'") == 0
+    if name not in cache:
+        cache[name] = os.system(name + ' -c "import test.test_support"') == 0
+    return cache[name]
 
 
 class AbstractCompatTests(AbstractPickleTests):
@@ -81,6 +83,9 @@ class AbstractCompatTests(AbstractPickleTests):
         self.assertTrue(self.python)
         self.assertTrue(self.module)
         self.assertTrue(self.error)
+        test_support.requires("xpickle")
+        if not have_python_version(self.python):
+            self.skipTest('%s not available' % self.python)
 
     def send_to_worker(self, python, obj, proto):
         """Bounce a pickled object through another version of Python.
@@ -119,14 +124,9 @@ class AbstractCompatTests(AbstractPickleTests):
 
     # These tests are disabled because they require some special setup
     # on the worker that's hard to keep in sync.
-    def test_global_ext1(self):
-        pass
-
-    def test_global_ext2(self):
-        pass
-
-    def test_global_ext4(self):
-        pass
+    test_global_ext1 = None
+    test_global_ext2 = None
+    test_global_ext4 = None
 
     # This is a cut-down version of pickletester's test_float. Backwards
     # compatibility for the values in for_bin_protos was explicitly broken in
@@ -151,48 +151,36 @@ class AbstractCompatTests(AbstractPickleTests):
                 self.assertEqual(value, got)
 
     # Backwards compatibility was explicitly broken in r67934 to fix a bug.
-    def test_unicode_high_plane(self):
-        pass
+    test_unicode_high_plane = None
 
     # This tests a fix that's in 2.7 only
-    def test_dynamic_class(self):
-        pass
-
-    if test_support.have_unicode:
-        # This is a cut-down version of pickletester's test_unicode. Backwards
-        # compatibility was explicitly broken in r67934 to fix a bug.
-        def test_unicode(self):
-            endcases = [u'', u'<\\u>', u'<\\\u1234>', u'<\n>', u'<\\>']
-            for proto in pickletester.protocols:
-                for u in endcases:
-                    p = self.dumps(u, proto)
-                    u2 = self.loads(p)
-                    self.assertEqual(u2, u)
-
-
-def run_compat_test(python_name):
-    return (test_support.is_resource_enabled("xpickle") and
-            have_python_version(python_name))
+    test_dynamic_class = None
+
+    # This is a cut-down version of pickletester's test_unicode. Backwards
+    # compatibility was explicitly broken in r67934 to fix a bug.
+    def test_unicode(self):
+        if not test_support.have_unicode:
+            # Python 2.5 has no unittest.skipUnless
+            self.skipTest('no unicode support')
+        endcases = [u'', u'<\\u>', u'<\\%c>' % 0x1234, u'<\n>', u'<\\>']
+        for proto in pickletester.protocols:
+            for u in endcases:
+                p = self.dumps(u, proto)
+                u2 = self.loads(p)
+                self.assertEqual(u2, u)
 
 
 # Test backwards compatibility with Python 2.4.
-if not run_compat_test("python2.4"):
-    class CPicklePython24Compat(unittest.TestCase):
-        pass
-else:
-    class CPicklePython24Compat(AbstractCompatTests):
+class CPicklePython24Compat(AbstractCompatTests):
 
-        module = cPickle
-        python = "python2.4"
-        error = cPickle.BadPickleGet
-
-        # Disable these tests for Python 2.4. Making them pass would require
-        # nontrivially monkeypatching the pickletester module in the worker.
-        def test_reduce_calls_base(self):
-            pass
+    module = cPickle
+    python = "python2.4"
+    error = cPickle.BadPickleGet
 
-        def test_reduce_ex_calls_base(self):
-            pass
+    # Disable these tests for Python 2.4. Making them pass would require
+    # nontrivially monkeypatching the pickletester module in the worker.
+    test_reduce_calls_base = None
+    test_reduce_ex_calls_base = None
 
 class PicklePython24Compat(CPicklePython24Compat):
 
@@ -201,15 +189,11 @@ class PicklePython24Compat(CPicklePython24Compat):
 
 
 # Test backwards compatibility with Python 2.5.
-if not run_compat_test("python2.5"):
-    class CPicklePython25Compat(unittest.TestCase):
-        pass
-else:
-    class CPicklePython25Compat(AbstractCompatTests):
+class CPicklePython25Compat(AbstractCompatTests):
 
-        module = cPickle
-        python = "python2.5"
-        error = cPickle.BadPickleGet
+    module = cPickle
+    python = "python2.5"
+    error = cPickle.BadPickleGet
 
 class PicklePython25Compat(CPicklePython25Compat):
 
@@ -218,15 +202,11 @@ class PicklePython25Compat(CPicklePython25Compat):
 
 
 # Test backwards compatibility with Python 2.6.
-if not run_compat_test("python2.6"):
-    class CPicklePython26Compat(unittest.TestCase):
-        pass
-else:
-    class CPicklePython26Compat(AbstractCompatTests):
+class CPicklePython26Compat(AbstractCompatTests):
 
-        module = cPickle
-        python = "python2.6"
-        error = cPickle.BadPickleGet
+    module = cPickle
+    python = "python2.6"
+    error = cPickle.BadPickleGet
 
 class PicklePython26Compat(CPicklePython26Compat):
 
@@ -234,6 +214,18 @@ class PicklePython26Compat(CPicklePython26Compat):
     error = KeyError
 
 
+class CPicklePython27Compat(AbstractCompatTests):
+
+    module = cPickle
+    python = "python2.7"
+    error = cPickle.BadPickleGet
+
+class PicklePython27Compat(CPicklePython27Compat):
+
+    module = pickle
+    error = KeyError
+
+
 def worker_main(in_stream, out_stream):
     message = cPickle.load(in_stream)
     protocol, obj = message
@@ -241,20 +233,17 @@ def worker_main(in_stream, out_stream):
 
 
 def test_main():
-    if not test_support.is_resource_enabled("xpickle"):
-        print >>sys.stderr, "test_xpickle -- skipping backwards compat tests."
-        print >>sys.stderr, "Use 'regrtest.py -u xpickle' to run them."
-        sys.stderr.flush()
-
     test_support.run_unittest(
         DumpCPickle_LoadPickle,
         DumpPickle_LoadCPickle,
         CPicklePython24Compat,
         CPicklePython25Compat,
         CPicklePython26Compat,
+        CPicklePython27Compat,
         PicklePython24Compat,
         PicklePython25Compat,
         PicklePython26Compat,
+        PicklePython27Compat,
     )
 
 if __name__ == "__main__":
index fbeda53..71c6605 100644 (file)
@@ -14,7 +14,7 @@ import unittest
 
 from StringIO import StringIO
 from tempfile import TemporaryFile
-from random import randint, random
+from random import randint, random, getrandbits
 from unittest import skipUnless
 
 from test.test_support import TESTFN, TESTFN_UNICODE, TESTFN_ENCODING, \
@@ -35,6 +35,8 @@ SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
                    ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
                    ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
 
+def getrandbytes(size):
+    return bytes(bytearray.fromhex('%0*x' % (2 * size, getrandbits(8 * size))))
 
 class TestsWithSourceFile(unittest.TestCase):
     def setUp(self):
@@ -773,7 +775,12 @@ class TestZip64InSmallFiles(unittest.TestCase):
 
 
 class PyZipFileTests(unittest.TestCase):
+    def requiresWriteAccess(self, path):
+        if not os.access(path, os.W_OK):
+            self.skipTest('requires write access to the installed location')
+
     def test_write_pyfile(self):
+        self.requiresWriteAccess(os.path.dirname(__file__))
         with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
             fn = __file__
             if fn.endswith('.pyc') or fn.endswith('.pyo'):
@@ -801,6 +808,7 @@ class PyZipFileTests(unittest.TestCase):
     def test_write_python_package(self):
         import email
         packagedir = os.path.dirname(email.__file__)
+        self.requiresWriteAccess(packagedir)
 
         with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
             zipfp.writepy(packagedir)
@@ -1168,8 +1176,7 @@ class OtherTests(unittest.TestCase):
         # than requested.
         for test_size in (1, 4095, 4096, 4097, 16384):
             file_size = test_size + 1
-            junk = b''.join(struct.pack('B', randint(0, 255))
-                            for x in range(file_size))
+            junk = getrandbytes(file_size)
             with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
                 zipf.writestr('foo', junk)
                 with zipf.open('foo', 'r') as fp:
@@ -1400,50 +1407,104 @@ class TestsWithRandomBinaryFiles(unittest.TestCase):
 
 @skipUnless(zlib, "requires zlib")
 class TestsWithMultipleOpens(unittest.TestCase):
-    def setUp(self):
+    @classmethod
+    def setUpClass(cls):
+        cls.data1 = b'111' + getrandbytes(10000)
+        cls.data2 = b'222' + getrandbytes(10000)
+
+    def make_test_archive(self, f):
         # Create the ZIP archive
-        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
-            zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
-            zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
+        with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
+            zipfp.writestr('ones', self.data1)
+            zipfp.writestr('twos', self.data2)
 
     def test_same_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.
+        self.make_test_archive(TESTFN2)
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
             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)
+                data1 += zopen1.read()
+                data2 += zopen2.read()
             self.assertEqual(data1, data2)
+            self.assertEqual(data1, self.data1)
 
     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.
+        self.make_test_archive(TESTFN2)
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
             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, '1'*FIXEDTEST_SIZE)
-            self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
+                data1 += zopen1.read()
+                data2 += zopen2.read()
+            self.assertEqual(data1, self.data1)
+            self.assertEqual(data2, self.data2)
 
     def test_interleaved(self):
         # Verify that (when the ZipFile is in control of creating file objects)
         # multiple open() calls can be made without interfering with each other.
+        self.make_test_archive(TESTFN2)
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
             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, '1'*FIXEDTEST_SIZE)
-            self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
+                data1 += zopen1.read()
+                data2 += zopen2.read()
+            self.assertEqual(data1, self.data1)
+            self.assertEqual(data2, self.data2)
+
+    def test_read_after_close(self):
+        self.make_test_archive(TESTFN2)
+        zopen1 = zopen2 = None
+        try:
+            with zipfile.ZipFile(TESTFN2, 'r') as zipf:
+                zopen1 = zipf.open('ones')
+                zopen2 = zipf.open('twos')
+            data1 = zopen1.read(500)
+            data2 = zopen2.read(500)
+            data1 += zopen1.read()
+            data2 += zopen2.read()
+        finally:
+            if zopen1:
+                zopen1.close()
+            if zopen2:
+                zopen2.close()
+        self.assertEqual(data1, self.data1)
+        self.assertEqual(data2, self.data2)
+
+    def test_read_after_write(self):
+        with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
+            zipf.writestr('ones', self.data1)
+            zipf.writestr('twos', self.data2)
+            with zipf.open('ones') as zopen1:
+                data1 = zopen1.read(500)
+        self.assertEqual(data1, self.data1[:500])
+        with zipfile.ZipFile(TESTFN2, 'r') as zipf:
+            data1 = zipf.read('ones')
+            data2 = zipf.read('twos')
+        self.assertEqual(data1, self.data1)
+        self.assertEqual(data2, self.data2)
+
+    def test_write_after_read(self):
+        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipf:
+            zipf.writestr('ones', self.data1)
+            with zipf.open('ones') as zopen1:
+                zopen1.read(500)
+                zipf.writestr('twos', self.data2)
+        with zipfile.ZipFile(TESTFN2, 'r') as zipf:
+            data1 = zipf.read('ones')
+            data2 = zipf.read('twos')
+        self.assertEqual(data1, self.data1)
+        self.assertEqual(data2, self.data2)
 
     def test_many_opens(self):
         # Verify that read() and open() promptly close the file descriptor,
         # and don't rely on the garbage collector to free resources.
+        self.make_test_archive(TESTFN2)
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
             for x in range(100):
                 zipf.read('ones')
index 9af92fb..92136da 100644 (file)
@@ -1,4 +1,4 @@
-<?xml version="1.0"?>
+<?xml version="1.0" encoding="iso-8859-1"?>
 <HTML xmlns:pp="http://www.isogen.com/paul/post-processor">
 <TITLE>Introduction to XSL</TITLE>
 <H1>Introduction to XSL</H1>
                </UL>
        
 
-
        
 </HTML>
index d4ab1ab..f7e9ad2 100644 (file)
                </UL>
        
 
-
        
 </HTML>
\ No newline at end of file
index 62ea0b4..e755860 100644 (file)
@@ -147,7 +147,7 @@ class TextWrapper:
         """_munge_whitespace(text : string) -> string
 
         Munge whitespace in text: expand tabs and convert all other
-        whitespace characters to spaces.  Eg. " foo\tbar\n\nbaz"
+        whitespace characters to spaces.  Eg. " foo\\tbar\\n\\nbaz"
         becomes " foo    bar  baz".
         """
         if self.expand_tabs:
@@ -193,7 +193,7 @@ class TextWrapper:
         """_fix_sentence_endings(chunks : [string])
 
         Correct for sentence endings buried in 'chunks'.  Eg. when the
-        original text contains "... foo.\nBar ...", munge_whitespace()
+        original text contains "... foo.\\nBar ...", munge_whitespace()
         and split() will convert that to [..., "foo.", " ", "Bar", ...]
         which has one too few spaces; this method simply changes the one
         space to two.
@@ -379,7 +379,7 @@ def dedent(text):
     in indented form.
 
     Note that tabs and spaces are both treated as whitespace, but they
-    are not equal: the lines "  hello" and "\thello" are
+    are not equal: the lines "  hello" and "\\thello" are
     considered to have no common leading whitespace.  (This behaviour is
     new in Python 2.5; older versions of this module incorrectly
     expanded tabs before searching for common leading whitespace.)
index da9e819..a8992f8 100755 (executable)
@@ -123,6 +123,12 @@ class Timer:
         self.timer = timer
         ns = {}
         if isinstance(stmt, basestring):
+            # Check that the code can be compiled outside a function
+            if isinstance(setup, basestring):
+                compile(setup, dummy_src_name, "exec")
+                compile(setup + '\n' + stmt, dummy_src_name, "exec")
+            else:
+                compile(stmt, dummy_src_name, "exec")
             stmt = reindent(stmt, 8)
             if isinstance(setup, basestring):
                 setup = reindent(setup, 4)
@@ -234,10 +240,10 @@ def repeat(stmt="pass", setup="pass", timer=default_timer,
     """Convenience function to create Timer object and call repeat method."""
     return Timer(stmt, setup, timer).repeat(repeat, number)
 
-def main(args=None):
+def main(args=None, _wrap_timer=None):
     """Main program, used when run as a script.
 
-    The optional argument specifies the command line to be parsed,
+    The optional 'args' argument specifies the command line to be parsed,
     defaulting to sys.argv[1:].
 
     The return value is an exit code to be passed to sys.exit(); it
@@ -246,6 +252,10 @@ def main(args=None):
     When an exception happens during timing, a traceback is printed to
     stderr and the return value is 1.  Exceptions at other times
     (including the template compilation) are not caught.
+
+    '_wrap_timer' is an internal interface used for unit testing.  If it
+    is not None, it must be a callable that accepts a timer function
+    and returns another timer function (used for unit testing).
     """
     if args is None:
         args = sys.argv[1:]
@@ -291,6 +301,8 @@ def main(args=None):
     # directory)
     import os
     sys.path.insert(0, os.curdir)
+    if _wrap_timer is not None:
+        timer = _wrap_timer(timer)
     t = Timer(stmt, setup, timer)
     if number == 0:
         # determine number so that 0.2 <= total time < 2.0
index ff90e04..d414f54 100644 (file)
@@ -82,3 +82,5 @@ GetSetDescriptorType = type(FunctionType.func_code)
 MemberDescriptorType = type(FunctionType.func_globals)
 
 del sys, _f, _g, _C, _x                           # Not for export
+
+__all__ = list(n for n in globals() if n[:1] != '_')
index 644fe5b..6bbc55f 100644 (file)
@@ -127,6 +127,8 @@ class _AssertRaisesContext(object):
                      (expected_regexp.pattern, str(exc_value)))
         return True
 
+def _sentinel(*args, **kwargs):
+    raise AssertionError('Should never be called')
 
 class TestCase(object):
     """A class whose instances are single test cases.
@@ -443,7 +445,7 @@ class TestCase(object):
             return  '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
 
 
-    def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
+    def assertRaises(self, excClass, callableObj=_sentinel, *args, **kwargs):
         """Fail unless an exception of class excClass is raised
            by callableObj when invoked with arguments args and keyword
            arguments kwargs. If a different type of exception is
@@ -451,7 +453,7 @@ class TestCase(object):
            deemed to have suffered an error, exactly as for an
            unexpected exception.
 
-           If called with callableObj omitted or None, will return a
+           If called with callableObj omitted, will return a
            context object used like this::
 
                 with self.assertRaises(SomeException):
@@ -467,7 +469,7 @@ class TestCase(object):
                self.assertEqual(the_exception.error_code, 3)
         """
         context = _AssertRaisesContext(excClass, self)
-        if callableObj is None:
+        if callableObj is _sentinel:
             return context
         with context:
             callableObj(*args, **kwargs)
@@ -973,7 +975,7 @@ class TestCase(object):
             self.fail(self._formatMessage(msg, standardMsg))
 
     def assertRaisesRegexp(self, expected_exception, expected_regexp,
-                           callable_obj=None, *args, **kwargs):
+                           callable_obj=_sentinel, *args, **kwargs):
         """Asserts that the message in a raised exception matches a regexp.
 
         Args:
@@ -987,7 +989,7 @@ class TestCase(object):
         if expected_regexp is not None:
             expected_regexp = re.compile(expected_regexp)
         context = _AssertRaisesContext(expected_exception, self, expected_regexp)
-        if callable_obj is None:
+        if callable_obj is _sentinel:
             return context
         with context:
             callable_obj(*args, **kwargs)
index 4ddf436..4c2d1f9 100644 (file)
@@ -954,6 +954,50 @@ test case
         self.assertRaises(self.failureException, self.assertRegexpMatches,
                           'saaas', r'aaaa')
 
+    def testAssertRaisesCallable(self):
+        class ExceptionMock(Exception):
+            pass
+        def Stub():
+            raise ExceptionMock('We expect')
+        self.assertRaises(ExceptionMock, Stub)
+        # A tuple of exception classes is accepted
+        self.assertRaises((ValueError, ExceptionMock), Stub)
+        # *args and **kwargs also work
+        self.assertRaises(ValueError, int, '19', base=8)
+        # Failure when no exception is raised
+        with self.assertRaises(self.failureException):
+            self.assertRaises(ExceptionMock, lambda: 0)
+        # Failure when the function is None
+        with self.assertRaises(TypeError):
+            self.assertRaises(ExceptionMock, None)
+        # Failure when another exception is raised
+        with self.assertRaises(ExceptionMock):
+            self.assertRaises(ValueError, Stub)
+
+    def testAssertRaisesContext(self):
+        class ExceptionMock(Exception):
+            pass
+        def Stub():
+            raise ExceptionMock('We expect')
+        with self.assertRaises(ExceptionMock):
+            Stub()
+        # A tuple of exception classes is accepted
+        with self.assertRaises((ValueError, ExceptionMock)) as cm:
+            Stub()
+        # The context manager exposes caught exception
+        self.assertIsInstance(cm.exception, ExceptionMock)
+        self.assertEqual(cm.exception.args[0], 'We expect')
+        # *args and **kwargs also work
+        with self.assertRaises(ValueError):
+            int('19', base=8)
+        # Failure when no exception is raised
+        with self.assertRaises(self.failureException):
+            with self.assertRaises(ExceptionMock):
+                pass
+        # Failure when another exception is raised
+        with self.assertRaises(ExceptionMock):
+            self.assertRaises(ValueError, Stub)
+
     def testAssertRaisesRegexp(self):
         class ExceptionMock(Exception):
             pass
@@ -964,6 +1008,8 @@ test case
         self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
         self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
         self.assertRaisesRegexp(ExceptionMock, u'expect$', Stub)
+        with self.assertRaises(TypeError):
+            self.assertRaisesRegexp(ExceptionMock, 'expect$', None)
 
     def testAssertNotRaisesRegexp(self):
         self.assertRaisesRegexp(
index 2408cb8..ccb0574 100644 (file)
@@ -871,7 +871,11 @@ class ftpwrapper:
         self.timeout = timeout
         self.refcount = 0
         self.keepalive = persistent
-        self.init()
+        try:
+            self.init()
+        except:
+            self.close()
+            raise
 
     def init(self):
         import ftplib
@@ -990,11 +994,16 @@ class addclosehook(addbase):
         self.hookargs = hookargs
 
     def close(self):
-        if self.closehook:
-            self.closehook(*self.hookargs)
-            self.closehook = None
-            self.hookargs = None
-        addbase.close(self)
+        try:
+            closehook = self.closehook
+            hookargs = self.hookargs
+            if closehook:
+                self.closehook = None
+                self.hookargs = None
+                closehook(*hookargs)
+        finally:
+            addbase.close(self)
+
 
 class addinfo(addbase):
     """class to add an info() method to an open file."""
index bf9a5d8..fbec94b 100644 (file)
@@ -26,6 +26,9 @@ def _show_warning(message, category, filename, lineno, file=None, line=None):
     """Hook to write a warning to a file; replace if you like."""
     if file is None:
         file = sys.stderr
+        if file is None:
+            # sys.stderr is None - warnings get lost
+            return
     try:
         file.write(formatwarning(message, category, filename, lineno, line))
     except IOError:
index 8ff93c3..97f2146 100644 (file)
@@ -180,10 +180,11 @@ class Wave_read:
         self._soundpos = 0
 
     def close(self):
-        if self._i_opened_the_file:
-            self._i_opened_the_file.close()
-            self._i_opened_the_file = None
         self._file = None
+        file = self._i_opened_the_file
+        if file:
+            self._i_opened_the_file = None
+            file.close()
 
     def tell(self):
         return self._soundpos
@@ -444,17 +445,18 @@ class Wave_write:
             self._patchheader()
 
     def close(self):
-        if self._file:
-            try:
+        try:
+            if self._file:
                 self._ensure_header_written(0)
                 if self._datalength != self._datawritten:
                     self._patchheader()
                 self._file.flush()
-            finally:
-                self._file = None
-        if self._i_opened_the_file:
-            self._i_opened_the_file.close()
-            self._i_opened_the_file = None
+        finally:
+            self._file = None
+            file = self._i_opened_the_file
+            if file:
+                self._i_opened_the_file = None
+                file.close()
 
     #
     # Internal methods.
index 9de3e72..21c9db9 100644 (file)
@@ -43,6 +43,9 @@ else:
     _mkproxy = weakref.proxy
     del weakref, _weakref
 
+class _ClosedParser:
+    pass
+
 # --- ExpatLocator
 
 class ExpatLocator(xmlreader.Locator):
@@ -214,14 +217,24 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
             self._err_handler.fatalError(exc)
 
     def close(self):
-        if self._entity_stack:
+        if (self._entity_stack or self._parser is None or
+            isinstance(self._parser, _ClosedParser)):
             # If we are completing an external entity, do nothing here
             return
-        self.feed("", isFinal = 1)
-        self._cont_handler.endDocument()
-        self._parsing = 0
-        # break cycle created by expat handlers pointing to our methods
-        self._parser = None
+        try:
+            self.feed("", isFinal = 1)
+            self._cont_handler.endDocument()
+            self._parsing = 0
+            # break cycle created by expat handlers pointing to our methods
+            self._parser = None
+        finally:
+            self._parsing = 0
+            if self._parser is not None:
+                # Keep ErrorColumnNumber and ErrorLineNumber after closing.
+                parser = _ClosedParser()
+                parser.ErrorColumnNumber = self._parser.ErrorColumnNumber
+                parser.ErrorLineNumber = self._parser.ErrorLineNumber
+                self._parser = parser
 
     def _reset_cont_handler(self):
         self._parser.ProcessingInstructionHandler = \
index 340dc51..db185a6 100644 (file)
@@ -558,8 +558,13 @@ else:
             self._parser.Parse(data, 0)
 
         def close(self):
-            self._parser.Parse("", 1) # end of data
-            del self._target, self._parser # get rid of circular references
+            try:
+                parser = self._parser
+            except AttributeError:
+                pass
+            else:
+                del self._target, self._parser # get rid of circular references
+                parser.Parse("", 1) # end of data
 
 class SlowParser:
     """Default XML parser (based on xmllib.XMLParser)."""
@@ -1214,8 +1219,10 @@ class GzipDecodedResponse(gzip.GzipFile if gzip else object):
         gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)
 
     def close(self):
-        gzip.GzipFile.close(self)
-        self.stringio.close()
+        try:
+            gzip.GzipFile.close(self)
+        finally:
+            self.stringio.close()
 
 
 # --------------------------------------------------------------------
@@ -1384,9 +1391,10 @@ class Transport:
     # Used in the event of socket errors.
     #
     def close(self):
-        if self._connection[1]:
-            self._connection[1].close()
+        host, connection = self._connection
+        if connection:
             self._connection = (None, None)
+            connection.close()
 
     ##
     # Send request header.
index 5a11350..6f6b20a 100644 (file)
@@ -30,7 +30,7 @@ yet integrated into ``build-installer.py``.
 
     - builds the following third-party libraries
 
-        * libcrypto and libssl from OpenSSL 1.0.1j
+        * libcrypto and libssl from OpenSSL 1.0.1
         * NCurses 5.9
         * SQLite 3.7.13
         * Oracle Sleepycat DB 4.8 (Python 2.x only)
index 5c9b590..8728289 100755 (executable)
@@ -237,9 +237,9 @@ def library_recipes():
 
         result.extend([
           dict(
-              name="OpenSSL 1.0.1j",
-              url="https://www.openssl.org/source/openssl-1.0.1j.tar.gz",
-              checksum='f7175c9cd3c39bb1907ac8bba9df8ed3',
+              name="OpenSSL 1.0.2a",
+              url="https://www.openssl.org/source/openssl-1.0.2a.tar.gz",
+              checksum='a06c547dac9044161a477211049f60ef',
               patches=[
                   "openssl_sdk_makedepend.patch",
                    ],
@@ -844,6 +844,11 @@ def build_universal_openssl(basedir, archList):
     separately then lipo them together into fat libraries.
     """
 
+    # OpenSSL fails to build with Xcode 2.5 (on OS X 10.4).
+    # If we are building on a 10.4.x or earlier system,
+    # unilaterally disable assembly code building to avoid the problem.
+    no_asm = int(platform.release().split(".")[0]) < 9
+
     def build_openssl_arch(archbase, arch):
         "Build one architecture of openssl"
         arch_opts = {
@@ -868,6 +873,8 @@ def build_universal_openssl(basedir, archList):
             "--prefix=%s"%os.path.join("/", *FW_VERSION_PREFIX),
             "--openssldir=/System/Library/OpenSSL",
         ]
+        if no_asm:
+            configure_opts.append("no-asm")
         runCommand(" ".join(["perl", "Configure"]
                         + arch_opts[arch] + configure_opts))
         runCommand("make depend OSX_SDK=%s" % SDKPATH)
@@ -1509,8 +1516,6 @@ def buildInstaller():
         else:
             patchFile(os.path.join('resources', fn), os.path.join(rsrcDir, fn))
 
-    shutil.copy("../../LICENSE", os.path.join(rsrcDir, 'License.txt'))
-
 
 def installSize(clear=False, _saved=[]):
     if clear:
@@ -1621,9 +1626,9 @@ def main():
     folder = os.path.join(WORKDIR, "_root", "Applications", "Python %s"%(
         getVersion(),))
     fn = os.path.join(folder, "License.rtf")
-    patchFile("resources/license.rtf",  fn)
+    patchFile("resources/License.rtf",  fn)
     fn = os.path.join(folder, "ReadMe.rtf")
-    patchFile("resources/readme.rtf",  fn)
+    patchFile("resources/ReadMe.rtf",  fn)
     fn = os.path.join(folder, "Update Shell Profile.command")
     patchScript("scripts/postflight.patch-profile",  fn)
     os.chmod(folder, STAT_0o755)
@@ -1633,10 +1638,12 @@ def main():
     buildInstaller()
 
     # And copy the readme into the directory containing the installer
-    patchFile('resources/ReadMe.txt', os.path.join(WORKDIR, 'installer', 'ReadMe.txt'))
+    patchFile('resources/ReadMe.rtf',
+                os.path.join(WORKDIR, 'installer', 'ReadMe.rtf'))
 
     # Ditto for the license file.
-    shutil.copy('../../LICENSE', os.path.join(WORKDIR, 'installer', 'License.txt'))
+    patchFile('resources/License.rtf',
+                os.path.join(WORKDIR, 'installer', 'License.rtf'))
 
     fp = open(os.path.join(WORKDIR, 'installer', 'Build.txt'), 'w')
     fp.write("# BUILD INFO\n")
index 6f95487..5903afd 100644 (file)
@@ -1,14 +1,18 @@
+# HG changeset patch
+# Parent  25a9af415e8c3faf591c360d5f0e361d049b2b43
 # openssl_sdk_makedepend.patch
 #
-#      using openssl 1.0.1j
+#      using openssl 1.0.2a
 #
 # - support building with an OS X SDK
 # - allow "make depend" to use compilers with names other than "gcc"
 
 diff Configure
---- a/Configure        Fri Dec 05 01:24:16 2014 -0800
-+++ b/Configure        Fri Dec 05 01:52:29 2014 -0800
-@@ -577,11 +577,11 @@
+
+diff --git a/Configure b/Configure
+--- a/Configure
++++ b/Configure
+@@ -617,12 +617,12 @@
  
  ##### MacOS X (a.k.a. Rhapsody or Darwin) setup
  "rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::",
@@ -16,16 +20,18 @@ diff Configure
 -"darwin64-ppc-cc","cc:-arch ppc64 -O3 -DB_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc64_asm}:osx64:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 -"darwin-i386-cc","cc:-arch i386 -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:".eval{my $asm=$x86_asm;$asm=~s/cast\-586\.o//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 -"debug-darwin-i386-cc","cc:-arch i386 -g3 -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:${x86_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
--"darwin64-x86_64-cc","cc:-arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
+-"darwin64-x86_64-cc","cc:-arch x86_64 -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
+-"debug-darwin64-x86_64-cc","cc:-arch x86_64 -ggdb -g2 -O0 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 +"darwin-ppc-cc","cc:-arch ppc -isysroot \$(OSX_SDK) -O3 -DB_ENDIAN -Wa,-force_cpusubtype_ALL::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 +"darwin64-ppc-cc","cc:-arch ppc64 -isysroot \$(OSX_SDK) -O3 -DB_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc64_asm}:osx64:dlfcn:darwin-shared:-fPIC -fno-common:-arch ppc64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 +"darwin-i386-cc","cc:-arch i386 -isysroot \$(OSX_SDK) -O3 -fomit-frame-pointer -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:".eval{my $asm=$x86_asm;$asm=~s/cast\-586\.o//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
 +"debug-darwin-i386-cc","cc:-arch i386 -isysroot \$(OSX_SDK) -g3 -DL_ENDIAN::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:BN_LLONG RC4_INT RC4_CHUNK DES_UNROLL BF_PTR:${x86_asm}:macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch i386 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
-+"darwin64-x86_64-cc","cc:-arch x86_64 -isysroot \$(OSX_SDK) -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHAR RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
++"darwin64-x86_64-cc","cc:-arch x86_64 -isysroot \$(OSX_SDK) -O3 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
++"debug-darwin64-x86_64-cc","cc:-arch x86_64 -isysroot \$(OSX_SDK) -ggdb -g2 -O0 -DL_ENDIAN -Wall::-D_REENTRANT:MACOSX:-Wl,-search_paths_first%:SIXTY_FOUR_BIT_LONG RC4_CHUNK DES_INT DES_UNROLL:".eval{my $asm=$x86_64_asm;$asm=~s/rc4\-[^:]+//;$asm}.":macosx:dlfcn:darwin-shared:-fPIC -fno-common:-arch x86_64 -dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
  "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
  # iPhoneOS/iOS
  "iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
-@@ -1624,7 +1624,7 @@
+@@ -1685,7 +1685,7 @@
                s/^CC=.*$/CC= $cc/;
                s/^AR=\s*ar/AR= $ar/;
                s/^RANLIB=.*/RANLIB= $ranlib/;
@@ -34,9 +40,9 @@ diff Configure
                }
        s/^CFLAG=.*$/CFLAG= $cflags/;
        s/^DEPFLAG=.*$/DEPFLAG=$depflags/;
-diff util/domd
---- a/util/domd        Fri Dec 05 01:24:16 2014 -0800
-+++ b/util/domd        Fri Dec 05 01:52:29 2014 -0800
+diff --git a/util/domd b/util/domd
+--- a/util/domd
++++ b/util/domd
 @@ -14,7 +14,7 @@
  cp Makefile Makefile.save
  # fake the presence of Kerberos
similarity index 92%
rename from Mac/BuildScript/resources/license.rtf
rename to Mac/BuildScript/resources/License.rtf
index 57dd46d..fff4d5b 100644 (file)
@@ -54,7 +54,7 @@ Thanks to the many outside volunteers who have worked under Guido's direction to
 \b0 \
 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation.\
 \
-2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee.\
+2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python.\
 \
@@ -124,22 +124,18 @@ Permission to use, copy, modify, and distribute this software and its documentat
 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\
 \
 \
-\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
 
-\b \cf0 \ul \ulc0 LICENSES AND ACKNOWLEDGEMENTS FOR INCORPORATED SOFTWARE\
-\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
+\b \ul LICENSES AND ACKNOWLEDGEMENTS FOR INCORPORATED SOFTWARE\
 
-\b0 \cf0 \ulnone \
+\b0 \ulnone \
 This installer incorporates portions of the following third-party software:\
 \
 
 \f2 $THIRD_PARTY_LIBS\
 \
-\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
 
-\f0 \cf0 For licenses and acknowledgements for these and other third-party software incorporated in this Python distribution, please refer to the on-line documentation {\field{\*\fldinst{HYPERLINK "https://docs.python.org/$VERSION/license.html#licenses-and-acknowledgements-for-incorporated-software"}}{\fldrslt here}}.\
-\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
-\cf0 \
+\f0 For licenses and acknowledgements for these and other third-party software incorporated in this Python distribution, please refer to the on-line documentation {\field{\*\fldinst{HYPERLINK "https://docs.python.org/$VERSION/license.html#licenses-and-acknowledgements-for-incorporated-software"}}{\fldrslt here}}.\
+\
 \
 \
 \
similarity index 92%
rename from Mac/BuildScript/resources/readme.rtf
rename to Mac/BuildScript/resources/ReadMe.rtf
index 25f89b8..368738f 100644 (file)
@@ -1,4 +1,4 @@
-{\rtf1\ansi\ansicpg1252\cocoartf1343\cocoasubrtf160
+{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
 {\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fmodern\fcharset0 CourierNewPSMT;}
 {\colortbl;\red255\green255\blue255;}
 \margl1440\margr1440\vieww15240\viewh15540\viewkind0
@@ -23,7 +23,7 @@ Python.org provides two installer variants for download: one that installs a
 \i $MACOSX_DEPLOYMENT_TARGET
 \i0  variant.  Unless you are installing to an 10.5 system or you need to build applications that can run on 10.5 systems, use the 10.6 variant if possible.  There are some additional operating system functions that are supported starting with 10.6 and you may see better performance using 64-bit mode.  By default, Python will automatically run in 64-bit mode if your system supports it.  Also see 
 \i Certificate verification and OpenSSL
-\i0  below.
+\i0  below.  The Pythons installed by these installers are built with private copies of some third-party libraries not included with or newer than those in OS X itself.  The list of these libraries varies by installer variant and is included at the end of the License.rtf file.
 \b \ul \
 \
 Update your version of Tcl/Tk to use IDLE or other Tk applications
@@ -41,9 +41,9 @@ Installing on OS X 10.8 (Mountain Lion) or later systems\
 \cf0 \ulnone [CHANGED for Python 2.7.9]
 \b0 \
 \
-As of Python 2.7.9, installer packages from python.org are now compatible with the Gatekeeper security feature introduced in OS X 10.8.   Downloaded packages can now be directly installed by double-clicking with the default system security settings.  Python.org installer packages for OS X are signed with the Developer ID of the builder, as identified on the download page for this release ({\field{\*\fldinst{HYPERLINK "https://www.python.org/downloads/"}}{\fldrslt https://www.python.org/downloads/}}).  To inspect the digital signature of the package, click on the lock icon in the upper right corner of the 
+As of Python 2.7.9, installer packages from python.org are now compatible with the Gatekeeper security feature introduced in OS X 10.8.   Downloaded packages can now be directly installed by double-clicking with the default system security settings.  Python.org installer packages for OS X are signed with the Developer ID of the builder, as identified on {\field{\*\fldinst{HYPERLINK "https://www.python.org/downloads/"}}{\fldrslt the download page}} for this release.  To inspect the digital signature of the package, click on the lock icon in the upper right corner of the 
 \i Install Python
-\i0  installer window.  Refer to Apple\'92s support pages for more information on Gatekeeper ({\field{\*\fldinst{HYPERLINK "http://support.apple.com/kb/ht5290"}}{\fldrslt http://support.apple.com/kb/ht5290}}).\
+\i0  installer window.  Refer to Apple\'92s support pages for {\field{\*\fldinst{HYPERLINK "http://support.apple.com/kb/ht5290"}}{\fldrslt more information on Gatekeeper}}.\
 \
 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
 
@@ -111,7 +111,7 @@ For OS X 10.5, Apple provides
 \i0 .  To solve this problem, as of 2.7.9 the 
 \i 10.5+ 32-bit-only python.org variant
 \i0  is linked with a private copy of 
-\i OpenSSL 1.0.1j
+\i OpenSSL 1.0
 \i0 ; it consults the same default certificate directory, 
 \f1 /System/Library/OpenSSL
 \f0 .   As before, it is still necessary to manage certificates yourself when you use this Python variant and, with certificate verification now enabled by default, you may now need to take additional steps to ensure your Python programs have access to CA certificates you trust.  If you use this Python variant to build standalone applications with third-party tools like {\field{\*\fldinst{HYPERLINK "https://pypi.python.org/pypi/py2app/"}}{\fldrslt 
diff --git a/Mac/BuildScript/resources/ReadMe.txt b/Mac/BuildScript/resources/ReadMe.txt
deleted file mode 100644 (file)
index 0aa6bc9..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-This package will install Python $FULL_VERSION for Mac OS X $MACOSX_DEPLOYMENT_TARGET for the following architecture(s): $ARCHITECTURES.
-
-=============================
-Which installer variant should I use?
-=============================
-
-Python.org provides two installer variants for download: one that installs a 64-bit/32-bit Intel Python capable of running on Mac OS X 10.6 (Snow Leopard) or later; and one that installs a 32-bit-only (Intel and PPC) Python capable of running on Mac OS X 10.5 (Leopard) or later.  This ReadMe was installed with the $MACOSX_DEPLOYMENT_TARGET variant.  Unless you are installing to an 10.5 system or you need to build applications that can run on 10.5 systems, use the 10.6 variant if possible.  There are some additional operating system functions that are supported starting with 10.6 and you may see better performance using 64-bit mode.  By default, Python will automatically run in 64-bit mode if your system supports it.  Also see Certificate verification and OpenSSL below.
-
-=============================
-Update your version of Tcl/Tk to use IDLE or other Tk applications
-=============================
-
-To use IDLE or other programs that use the Tkinter graphical user interface toolkit, you need to install a newer third-party version of the Tcl/Tk frameworks.  Visit https://www.python.org/download/mac/tcltk/ for current information about supported and recommended versions of Tcl/Tk for this version of Python and of Mac OS X.
-
-=============================
-Installing on OS X 10.8 (Mountain Lion) or later systems
-[CHANGED for Python 2.7.9]
-=============================
-
-As of Python 2.7.9, installer packages from python.org are now compatible with the Gatekeeper security feature introduced in OS X 10.8.   Downloaded packages can now be directly installed by double-clicking with the default system security settings.  Python.org installer packages for OS X are signed with the Developer ID of the builder, as identified on the download page for this release (https://www.python.org/downloads/).  To inspect the digital signature of the package, click on the lock icon in the upper right corner of the Install Python installer window.  Refer to Apple’s support pages for more information on Gatekeeper (http://support.apple.com/kb/ht5290).
-
-=============================
-Simplified web-based installs
-[NEW for Python 2.7.9]
-=============================
-
-With the change to the newer flat format installer package, the download file now has a .pkg extension as it is no longer necessary to embed the installer within a disk image (.dmg) container.   If you download the Python installer through a web browser, the OS X installer application may open automatically to allow you to perform the install.  If your browser settings do not allow automatic open, double click on the downloaded installer file.
-
-=============================
-New Installation Options and Defaults
-[NEW for Python 2.7.9]
-=============================
-
-The Python installer now includes an option to automatically install or upgrade pip, a tool for installing and managing Python packages.  This option is enabled by default and no Internet access is required.  If you do not want the installer to do this, select the Customize option at the Installation Type step and uncheck the Install or upgrade pip option.  For other changes in this release, see the Release Notes link for this release at https://www.python.org/downloads/.
-
-=============================
-Certificate verification and OpenSSL
-[CHANGED for Python 2.7.9]
-=============================
-
-Python 2.7.9 includes a number of network security enhancements that have been approved for inclusion in Python 2.7 maintenance releases.  PEP 476 changes several standard library modules, like httplib, urllib2, and xmlrpclib, to by default verify certificates presented by servers over secure (TLS) connections.  The verification is performed by the OpenSSL libraries that Python is linked to.  Prior to 2.7.9, the python.org installers dynamically linked with Apple-supplied OpenSSL libraries shipped with OS X.  OS X provides a multiple level security framework that stores trust certificates in system and user keychains managed by the Keychain Access application and the security command line utility.
-
-For OS X 10.5, Apple provides OpenSSL 0.9.7 libraries.  This version of Apple's OpenSSL does not use the certificates from the system security framework, even when used on newer versions of OS X.  Instead it consults a traditional OpenSSL concatenated certificate file (cafile) or certificate directory (capath), located in /System/Library/OpenSSL.  These directories are typically empty and not managed by OS X; you must manage them yourself or supply your own SSL contexts.  OpenSSL 0.9.7 is obsolete by current security standards, lacking a number of important features found in later versions.  Among the problems this causes is the inability to verify higher-security certificates now used by python.org services, including the Python Package Index, PyPI.  To solve this problem, as of 2.7.9 the 10.5+ 32-bit-only python.org variant is linked with a private copy of OpenSSL 1.0.1j; it consults the same default certificate directory, /System/Library/OpenSSL.   As before, it is still necessary to manage certificates yourself when you use this Python variant and, with certificate verification now enabled by default, you may now need to take additional steps to ensure your Python programs have access to CA certificates you trust.  If you use this Python variant to build standalone applications with third-party tools like py2app, you may now need to bundle CA certificates in them or otherwise supply non-default SSL contexts.
-
-For OS X 10.6+, Apple also provides OpenSSL 0.9.8 libraries.  Apple's 0.9.8 version includes an important additional feature: if a certificate cannot be verified using the manually administered certificates in /System/Library/OpenSSL, the certificates managed by the system security framework In the user and system keychains are also consulted (using Apple private APIs).  For this reason, for 2.7.9 the 64-bit/32-bit 10.6+ python.org variant continues to be dynamically linked with Apple's OpenSSL 0.9.8 since it was felt that the loss of the system-provided certificates and management tools outweighs the additional security features provided by newer versions of OpenSSL.  This will likely change in future releases of the python.org installers as Apple has deprecated use of the system-supplied OpenSSL libraries.  If you do need features from newer versions of OpenSSL, there are third-party OpenSSL wrapper packages available through PyPI.
-
-The bundled pip included with 2.7.9 has its own default certificate store for verifying download connections.
-
-=============================
-Binary installer support for OS X 10.4 and 10.3.9 discontinued
-[CHANGED for Python 2.7.9]
-=============================
-
-As previously announced, binary installers for Python 2.7.9 from python.org no longer support Mac OS X 10.3.9 (Panther) and 10.4.x (Tiger) systems.  These systems were last updated by Apple in 2005 and 2007.  As of 2.7.9, the 32-bit-only installer supports PPC and Intel Macs running OS X 10.5 (Leopard). 10.5 was the last OS X release for PPC machines (G4 and G5).  The 64-/32-bit installer configuration remains unchanged and should normally be used on OS X 10.6 (Snow Leopard) and later systems.  This aligns Python 2.7.x installer configurations with those currently provided with Python 3.x.  If needed, it is still possible to build Python from source for 10.3.9 and 10.4.
-
-=============================
-Python 3 and Python 2 Co-existence
-=============================
-
-Python.org Python 2.7 and 3.x versions can both be installed on your system and will not conflict.  Python 2 command names contain a 2 or no digit: python2 (or python2.7 or python), idle2 (or idle2.7 or idle), pip2 (or pip2.7 or pip), etc.  Command names for Python 3 contain a 3 in them: python3, idle3, pip3, etc.
index e793abb..ea15e0b 100644 (file)
 \b NEW for Python 2.7.9: 
 \b0 This package installs a version of 
 \f1 pip
-\f0 , the recommended tool for installing and managing Python packages.   Type\
-\
-       
+\f0 , the recommended tool for installing and managing Python packages.   Type 
 \f1 pip2.7 --help
-\f0 \
-\
-for an overview.  2.7.9 also includes a number of network security enhancements that may require changes to your Python applications.  See the 
+\f0  for an overview.  2.7.9 also includes a number of network security enhancements that may require changes to your Python applications.  See the 
 \f1 ReadMe
 \f0  file and {\field{\*\fldinst{HYPERLINK "https://docs.python.org/2/whatsnew/2.7.html#new-features-added-to-python-2-7-maintenance-releases"}}{\fldrslt the Python documentation}} for more information.\
 \
index 9a18b27..6efcba1 100644 (file)
@@ -36,7 +36,7 @@
        <key>CFBundleExecutable</key>
        <string>IDLE</string>
        <key>CFBundleGetInfoString</key>
-       <string>%VERSION%, © 2001-2014 Python Software Foundation</string>
+       <string>%VERSION%, © 2001-2015 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>IDLE.icns</string>
        <key>CFBundleIdentifier</key>
index 0a5a439..42846ea 100644 (file)
@@ -40,7 +40,7 @@
        <key>CFBundleExecutable</key>
        <string>PythonLauncher</string>
        <key>CFBundleGetInfoString</key>
-       <string>%VERSION%, © 2001-2014 Python Software Foundation</string>
+       <string>%VERSION%, © 2001-2015 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>PythonLauncher.icns</string>
        <key>CFBundleIdentifier</key>
index 93b1c44..cb7e8d7 100644 (file)
@@ -20,7 +20,7 @@
        <key>CFBundleExecutable</key>
        <string>Python</string>
        <key>CFBundleGetInfoString</key>
-       <string>%version%, (c) 2004-2014 Python Software Foundation.</string>
+       <string>%version%, (c) 2001-2015 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-2014 Python Software Foundation.</string>
+       <string>%version%, (c) 2001-2015 Python Software Foundation.</string>
        <key>CFBundleName</key>
        <string>Python</string>
        <key>CFBundlePackageType</key>
@@ -55,7 +55,7 @@
        <key>NSAppleScriptEnabled</key>
        <true/>
        <key>NSHumanReadableCopyright</key>
-       <string>(c) 2014 Python Software Foundation.</string>
+       <string>(c) 2001-2015 Python Software Foundation.</string>
        <key>NSHighResolutionCapable</key>
        <true/>
 </dict>
index 43a5740..a97cc1f 100644 (file)
@@ -17,9 +17,9 @@
        <key>CFBundlePackageType</key>
        <string>FMWK</string>
        <key>CFBundleShortVersionString</key>
-       <string>%VERSION%, (c) 2004-2014 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2015 Python Software Foundation.</string>
        <key>CFBundleLongVersionString</key>
-       <string>%VERSION%, (c) 2004-2014 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2015 Python Software Foundation.</string>
        <key>CFBundleSignature</key>
        <string>????</string>
        <key>CFBundleVersion</key>
index 7f4ec2f..b3b2b36 100644 (file)
@@ -946,7 +946,7 @@ maninstall: altmaninstall
        (cd $(DESTDIR)$(MANDIR)/man1; $(LN) -s python2.1 python.1)
 
 # Install the library
-PLATDIR=       plat-$(MACHDEP)
+PLATDIR=       @PLATDIR@
 EXTRAPLATDIR= @EXTRAPLATDIR@
 EXTRAMACHDEPPATH=@EXTRAMACHDEPPATH@
 MACHDEPS=      $(PLATDIR) $(EXTRAPLATDIR)
index d44240f..2262c79 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -95,6 +95,7 @@ Mike Bayer
 Samuel L. Bayer
 Donald Beaudry
 David Beazley
+Carlo Beccarini
 Neal Becker
 Robin Becker
 Torsten Becker
@@ -325,6 +326,7 @@ Raghuram Devarakonda
 Caleb Deveraux
 Catherine Devlin
 Scott Dial
+Alon Diamant
 Toby Dickenson
 Mark Dickinson
 Jack Diederich
@@ -339,6 +341,7 @@ Robert Donohue
 Marcos Donolo
 Dima Dorfman
 Yves Dorfsman
+Michael Dorman
 Cesar Douady
 Dean Draayer
 Fred L. Drake, Jr.
@@ -411,6 +414,7 @@ Vincent Fiack
 Anastasia Filatova
 Tomer Filiba
 Jeffrey Finkelstein
+Florian Finkernagel
 Russell Finn
 Dan Finnie
 Nils Fischbeck
@@ -475,6 +479,7 @@ Yannick Gingras
 Matt Giuca
 Wim Glenn
 Michael Goderbauer
+Karan Goel
 Jeroen Van Goey
 Christoph Gohlke
 Tim Golden
@@ -517,6 +522,7 @@ Mark Hammond
 Harald Hanche-Olsen
 Manus Hand
 Milton L. Hankins
+Richard Hansen
 Stephen Hansen
 Barry Hantman
 Lynda Hardman
@@ -680,6 +686,7 @@ Janne Karila
 Per Øyvind Karlsen
 Anton Kasyanov
 Lou Kates
+Makoto Kato
 Hiroaki Kawai
 Brian Kearns
 Sebastien Keim
@@ -1010,6 +1017,7 @@ Todd R. Palmer
 Juan David Ibáñez Palomar
 Jan Palus
 Yongzhi Pan
+Martin Panter
 Mathias Panzenböck
 M. Papillon
 Peter Parente
@@ -1070,7 +1078,9 @@ Martin Pool
 Iustin Pop
 Claudiu Popa
 John Popplewell
+Davin Potts
 Guillaume Pratte
+Florian Preinstorfer
 Amrit Prem
 Paul Prescod
 Donovan Preston
@@ -1165,6 +1175,7 @@ Sam Rushing
 Mark Russell
 Rusty Russell
 Nick Russo
+James Rutherford
 Chris Ryland
 Constantina S.
 Patrick Sabin
@@ -1308,6 +1319,7 @@ Hisao Suzuki
 Kalle Svensson
 Andrew Svetlov
 Paul Swartz
+Al Sweigart
 Thenault Sylvain
 Péter Szabó
 John Szakmeister
index fe3e9d7..c311f6b 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -2,6 +2,308 @@
 Python News
 +++++++++++
 
+What's New in Python 2.7.10?
+============================
+
+*Release date: 2015-05-23*
+
+Library
+-------
+
+- Issue #22931: Allow '[' and ']' in cookie values.
+
+
+What's New in Python 2.7.10 release candidate 1?
+================================================
+
+*Release date: 2015-05-10*
+
+Core and Builtins
+-----------------
+
+- Issue #20274: When calling a _sqlite.Connection, it now complains if passed
+  any keyword arguments.  Previously it silently ignored them.
+
+- Issue #20274: Remove ignored and erroneous "kwargs" parameters from three
+  METH_VARARGS methods on _sqlite.Connection.
+
+- Issue #23629: Fix the default __sizeof__ implementation for variable-sized
+  objects.
+
+- Issue #23055: Fixed a buffer overflow in PyUnicode_FromFormatV.  Analysis
+  and fix by Guido Vranken.
+
+- Issue #23048: Fix jumping out of an infinite while loop in the pdb.
+
+Library
+-------
+
+- The keywords attribute of functools.partial is now always a dictionary.
+
+- Issue #24134: assertRaises() and assertRaisesRegexp() checks are not longer
+  successful if the callable is None.
+
+- Issue #23008: Fixed resolving attributes with boolean value is False in pydoc.
+
+- Issues #24099, #24100, and #24101: Fix free-after-use bug in heapq's siftup
+  and siftdown functions.
+
+- Backport collections.deque fixes from Python 3.5.  Prevents reentrant badness
+  during deletion by deferring the decref until the container has been restored
+  to a consistent state.
+
+- Issue #23842: os.major(), os.minor() and os.makedev() now support ints again.
+
+- Issue #23811: Add missing newline to the PyCompileError error message.
+  Patch by Alex Shkop.
+
+- Issue #17898: Fix exception in gettext.py when parsing certain plural forms.
+
+- Issue #23865: close() methods in multiple modules now are idempotent and more
+  robust at shutdown. If they need to release multiple resources, all are
+  released even if errors occur.
+
+- Issue #23881: urllib.ftpwrapper constructor now closes the socket if the FTP
+  connection failed.
+
+- Issue #15133: _tkinter.tkapp.getboolean() now supports long and Tcl_Obj and
+  always returns bool.  tkinter.BooleanVar now validates input values (accepted
+  bool, int, long, str, unicode, and Tcl_Obj).  tkinter.BooleanVar.get() now
+  always returns bool.
+
+- Issue #23338: Fixed formatting ctypes error messages on Cygwin.
+  Patch by Makoto Kato.
+
+- Issue #16840: Tkinter now supports 64-bit integers added in Tcl 8.4 and
+  arbitrary precision integers added in Tcl 8.5.
+
+- Issue #23834: Fix socket.sendto(), use the C long type to store the result of
+  sendto() instead of the C int type.
+
+- Issue #21526: Tkinter now supports new boolean type in Tcl 8.5.
+
+- Issue #23838: linecache now clears the cache and returns an empty result on
+  MemoryError.
+
+- Issue #23742: ntpath.expandvars() no longer loses unbalanced single quotes.
+
+- Issue #21802: The reader in BufferedRWPair now is closed even when closing
+  writer failed in BufferedRWPair.close().
+
+- Issue #23671: string.Template now allows to specify the "self" parameter as
+  keyword argument.  string.Formatter now allows to specify the "self" and
+  the "format_string" parameters as keyword arguments.
+
+- Issue #21560: An attempt to write a data of wrong type no longer cause
+  GzipFile corruption.  Original patch by Wolfgang Maier.
+
+- Issue #23647: Increase impalib's MAXLINE to accommodate modern mailbox sizes.
+
+- Issue #23539: If body is None, http.client.HTTPConnection.request now sets
+  Content-Length to 0 for PUT, POST, and PATCH headers to avoid 411 errors from
+  some web servers.
+
+- Issue #23136: _strptime now uniformly handles all days in week 0, including
+  Dec 30 of previous year.  Based on patch by Jim Carroll.
+
+- Issue #23138: Fixed parsing cookies with absent keys or values in cookiejar.
+  Patch by Demian Brecht.
+
+- Issue #23051: multiprocessing.Pool methods imap() and imap_unordered() now
+  handle exceptions raised by an iterator.  Patch by Alon Diamant and Davin
+  Potts.
+
+- Issue #22928: Disabled HTTP header injections in httplib.
+  Original patch by Demian Brecht.
+
+- Issue #23615: Module tarfile is now can be reloaded with imp.reload().
+
+- Issue #22853: Fixed a deadlock when use multiprocessing.Queue at import time.
+  Patch by Florian Finkernagel and Davin Potts.
+
+- Issue #23476: In the ssl module, enable OpenSSL's X509_V_FLAG_TRUSTED_FIRST
+  flag on certificate stores when it is available.
+
+- Issue #23576: Avoid stalling in SSL reads when EOF has been reached in the
+  SSL layer but the underlying connection hasn't been closed.
+
+- Issue #23504: Added an __all__ to the types module.
+
+- Issue #23458: On POSIX, the file descriptor kept open by os.urandom() is now
+  set to non inheritable
+
+- Issue #22113: struct.pack_into() now supports new buffer protocol (in
+  particular accepts writable memoryview).
+
+- Issues #814253, #9179: Warnings now are raised when group references and
+  conditional group references are used in lookbehind assertions in regular
+  expressions.
+
+- Issue #23215: Multibyte codecs with custom error handlers that ignores errors
+  consumed too much memory and raised SystemError or MemoryError.
+  Original patch by Aleksi Torhamo.
+
+- Issue #5700: io.FileIO() called flush() after closing the file.
+  flush() was not called in close() if closefd=False.
+
+- Issue #21548: Fix pydoc.synopsis() and pydoc.apropos() on modules with empty
+  docstrings.  Initial patch by Yuyang Guo.
+
+- Issue #22885: Fixed arbitrary code execution vulnerability in the dumbdbm
+  module.  Original patch by Claudiu Popa.
+
+- Issue #23481: Remove RC4 from the SSL module's default cipher list.
+
+- Issue #21849: Fixed xmlrpclib serialization of non-ASCII unicode strings in
+  the multiprocessing module.
+
+- Issue #21840: Fixed expanding unicode variables of form $var in
+  posixpath.expandvars().  Fixed all os.path implementations on
+  unicode-disabled builds.
+
+- Issue #23367: Fix possible overflows in the unicodedata module.
+
+- Issue #23363: Fix possible overflow in itertools.permutations.
+
+- Issue #23364: Fix possible overflow in itertools.product.
+
+- Issue #23365: Fixed possible integer overflow in
+  itertools.combinations_with_replacement.
+
+- Issue #23366: Fixed possible integer overflow in itertools.combinations.
+
+- Issue #23191: fnmatch functions that use caching are now threadsafe.
+
+- Issue #18518: timeit now rejects statements which can't be compiled outside
+  a function or a loop (e.g. "return" or "break").
+
+- Issue #19996: Make :mod:`httplib` ignore headers with no name rather than
+  assuming the body has started.
+
+- Issue #20188: Support Application-Layer Protocol Negotiation (ALPN) in the ssl
+  module.
+
+- Issue #23248: Update ssl error codes from latest OpenSSL git master.
+
+- Issue #23098: 64-bit dev_t is now supported in the os module.
+
+- Issue #23063: In the disutils' check command, fix parsing of reST with code or
+  code-block directives.
+
+- Issue #21356: Make ssl.RAND_egd() optional to support LibreSSL. The
+  availability of the function is checked during the compilation. Patch written
+  by Bernard Spil.
+
+- Backport the context argument to ftplib.FTP_TLS.
+
+- Issue #23111: Maximize compatibility in protocol versions of ftplib.FTP_TLS.
+
+- Issue #23112: Fix SimpleHTTPServer to correctly carry the query string and
+  fragment when it redirects to add a trailing slash.
+
+- Issue #22585: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(),
+  instead of reading /dev/urandom, to get pseudo-random bytes.
+
+- Issue #23093: In the io, module allow more operations to work on detached
+  streams.
+
+- Issue #23071: Added missing names to codecs.__all__.  Patch by Martin Panter.
+
+- Issue #23016: A warning no longer produces an AttributeError when sys.stderr
+  is None.
+
+- Issue #21032. Fixed socket leak if HTTPConnection.getresponse() fails.
+  Original patch by Martin Panter.
+
+- Issue #22609: Constructors and update methods of mapping classes in the
+  collections module now accept the self keyword argument.
+
+Documentation
+-------------
+
+- Issue #23006: Improve the documentation and indexing of dict.__missing__.
+  Add an entry in the language datamodel special methods section.
+  Revise and index its discussion in the stdtypes mapping/dict section.
+  Backport the code example from 3.4.
+
+- Issue #21514: The documentation of the json module now refers to new JSON RFC
+  7159 instead of obsoleted RFC 4627.
+
+Tools/Demos
+-----------
+
+- Issue #23330: h2py now supports arbitrary filenames in #include.
+
+- Issue #6639: Module-level turtle functions no longer raise TclError after
+  closing the window.
+
+- Issue #22314: pydoc now works when the LINES environment variable is set.
+
+- Issue #18905: "pydoc -p 0" now outputs actually used port.  Based on patch by
+  Wieland Hoffmann.
+
+- Issue #23345: Prevent test_ssl failures with large OpenSSL patch level
+  values (like 0.9.8zc).
+
+Tests
+-----
+
+- Issue #23799: Added test.test_support.start_threads() for running and
+  cleaning up multiple threads.
+
+- Issue #22390: test.regrtest now emits a warning if temporary files or
+  directories are left after running a test.
+
+- Issue #23583: Added tests for standard IO streams in IDLE.
+
+- Issue #23392: Added tests for marshal C API that works with FILE*.
+
+- Issue #18982: Add tests for CLI of the calendar module.
+
+- Issue #19949: The test_xpickle test now tests compatibility with installed
+  Python 2.7 and reports skipped tests.  Based on patch by Zachary Ware.
+
+- Issue #11578: Backported test for the timeit module.
+
+- Issue #22943: bsddb tests are locale independend now.
+
+IDLE
+----
+
+- Issue #23583: Fixed writing unicode to standard output stream in IDLE.
+
+- Issue #20577: Configuration of the max line length for the FormatParagraph
+  extension has been moved from the General tab of the Idle preferences dialog
+  to the FormatParagraph tab of the Config Extensions dialog.
+  Patch by Tal Einat.
+
+- Issue #16893: Update Idle doc chapter to match current Idle and add new
+  information.
+
+- Issue #23180: Rename IDLE "Windows" menu item to "Window".
+  Patch by Al Sweigart.
+
+Build
+-----
+
+- Issue #15506: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the configure
+  script.
+
+- Issue #23032: Fix installer build failures on OS X 10.4 Tiger
+  by disabling assembly code in the OpenSSL build.
+
+- Issue #23686: Update OS X 10.5 installer and Windows builds to use
+  OpenSSL 1.0.2a.
+
+C API
+-----
+
+- Issue #23998: PyImport_ReInitLock() now checks for lock allocation error
+
+- Issue #22079: PyType_Ready() now checks that statically allocated type has
+  no dynamically allocated bases.
+
+
 What's New in Python 2.7.9?
 ===========================
 
@@ -105,7 +407,7 @@ Library
 
 - Issue #22776: Brought excluded code into the scope of a try block in
   SysLogHandler.emit().
+
 - Issue #17381: Fixed ranges handling in case-insensitive regular expressions.
 
 - Issue #19329: Optimized compiling charsets in regular expressions.
@@ -300,6 +602,23 @@ Library
 IDLE
 ----
 
+- Issue #3068: Add Idle extension configuration dialog to Options menu.
+  Changes are written to HOME/.idlerc/config-extensions.cfg.
+  Original patch by Tal Einat.
+
+- Issue #16233: A module browser (File : Class Browser, Alt+C) requires a
+  editor window with a filename.  When Class Browser is requested otherwise,
+  from a shell, output window, or 'Untitled' editor, Idle no longer displays
+  an error box.  It now pops up an  Open Module box (Alt+M). If a valid name
+  is entered and a module is opened, a corresponding browser is also opened.
+
+- Issue #4832: Save As to type Python files automatically adds .py to the
+  name you enter (even if your system does not display it).  Some systems
+  automatically add .txt when type is Text files.
+
+- Issue #21986: Code objects are not normally pickled by the pickle module.
+  To match this, they are no longer pickled when running under Idle.
+
 - Issue #22221: IDLE now ignores the source encoding declaration on the second
   line if the first line contains anything except a comment.
 
index bb98b3d..cacadb3 100644 (file)
@@ -34,7 +34,6 @@ 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
diff --git a/Misc/RPM/README b/Misc/RPM/README
deleted file mode 100644 (file)
index f3a2557..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-This directory contains support file used to build RPM releases of
-Python.  Its contents are maintained by Sean Reifschneider
-<jafo@tummy.com>.
-
-It is recommended that RPM builders use the python*.src.rpm file
-downloaded from the "ftp.python.org:/pub/python/<version>/rpms".  These
-may be more up to date than the files included in the base Python
-release tar-file.
-
-If you wish to build RPMs from the base Python release tar-file, note
-that you will have to download the
-"doc/<version>/html-<version>.tar.bz2"
-file from python.org and place it into your "SOURCES" directory for
-the build to complete.  This is the same directory that you place the
-Python-2.3.1 release tar-file in.  You can then use the ".spec" file in
-this directory to build RPMs.
diff --git a/Misc/RPM/python-2.7.spec b/Misc/RPM/python-2.7.spec
deleted file mode 100644 (file)
index fec5795..0000000
+++ /dev/null
@@ -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 2.7.9
-%define libvers 2.7
-#--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@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@tummy.com> [2.4-2pydotorg]
-- Changing the idle wrapper so that it passes arguments to idle.
-
-* Tue Oct 19 2004 Sean Reifschneider <jafo-rpms@tummy.com> [2.4b1-1pydotorg]
-- Updating to 2.4.
-
-* Thu Jul 22 2004 Sean Reifschneider <jafo-rpms@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@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@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@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@tummy.com> [2.3.2-1pydotorg]
-- Adding code to detect wether documentation is available to build.
-
-* Fri Sep 19 2003 Sean Reifschneider <jafo-rpms@tummy.com> [2.3.1-1pydotorg]
-- Updating to the 2.3.1 release.
-
-* Mon Feb 24 2003 Sean Reifschneider <jafo-rpms@tummy.com> [2.3b1-1pydotorg]
-- Updating to 2.3b1 release.
-
-* Mon Feb 17 2003 Sean Reifschneider <jafo-rpms@tummy.com> [2.3a1-1]
-- Updating to 2.3 release.
-
-* Sun Dec 23 2001 Sean Reifschneider <jafo-rpms@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@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@tummy.com>
-[Release 2.2c1-1]
-- Updated to 2.2c1.
-
-* Thu Nov  1 2001 Sean Reifschneider <jafo-rpms@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@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@tummy.com>
-[Release 2.2b1-1]
-- Updated to 2.2b1.
-
-* Mon Oct  9 2001 Sean Reifschneider <jafo-rpms@tummy.com>
-[Release 2.2a4-4]
-- otto@balinor.mat.unimi.it mentioned that the license file is missing.
-
-* Sun Sep 30 2001 Sean Reifschneider <jafo-rpms@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@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@tummy.com as well.
-   *****************************************************
-@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}/lib-tk
-%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload/_tkinter.so*
-%endif
-
-%if %{include_docs}
-%files docs
-%defattr(-,root,root)
-%{config_htmldir}/*
-%endif
index f869e7c..2647758 100644 (file)
@@ -212,12 +212,11 @@ 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 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.
 
index 39edbca..d87902f 100644 (file)
@@ -87,8 +87,7 @@ python \- an interpreted, interactive, object-oriented programming language
 .SH DESCRIPTION
 Python is an interpreted, interactive, object-oriented programming
 language that combines remarkable power with very clear syntax.
-For an introduction to programming in Python you are referred to the
-Python Tutorial.
+For an introduction to programming in Python, see the Python Tutorial.
 The Python Library Reference documents built-in and standard types,
 constants, functions and modules.
 Finally, the Python Reference Manual describes the syntax and
@@ -453,17 +452,17 @@ The integer must be a decimal number in the range [0,4294967295].  Specifying
 the value 0 will lead to the same hash values as when hash randomization is
 disabled.
 .SH AUTHOR
-The Python Software Foundation: http://www.python.org/psf
+The Python Software Foundation: https://www.python.org/psf
 .SH INTERNET RESOURCES
-Main website:  http://www.python.org/
+Main website:  https://www.python.org/
 .br
-Documentation:  http://docs.python.org/
+Documentation:  https://docs.python.org/2/
 .br
-Developer resources:  http://docs.python.org/devguide/
+Developer resources:  https://docs.python.org/devguide/
 .br
-Downloads:  http://python.org/download/
+Downloads:  https://www.python.org/downloads/
 .br
-Module repository:  http://pypi.python.org/
+Module repository:  https://pypi.python.org/
 .br
 Newsgroups:  comp.lang.python, comp.lang.python.announce
 .SH LICENSING
index 2ad1aa3..523e05a 100644 (file)
@@ -91,7 +91,7 @@ SITEPATH=
 TESTPATH=
 
 # Path components for machine- or system-dependent modules and shared libraries
-MACHDEPPATH=:plat-$(MACHDEP)
+MACHDEPPATH=:$(PLATDIR)
 EXTRAMACHDEPPATH=
 
 # Path component for the Tkinter-related modules
index bcdffcb..5080a5b 100644 (file)
@@ -623,9 +623,9 @@ deque_remove(dequeobject *deque, PyObject *value)
         if (cmp > 0) {
             PyObject *tgt = deque_popleft(deque, NULL);
             assert (tgt != NULL);
-            Py_DECREF(tgt);
-            if (_deque_rotate(deque, i) == -1)
+            if (_deque_rotate(deque, i))
                 return NULL;
+            Py_DECREF(tgt);
             Py_RETURN_NONE;
         }
         else if (cmp < 0) {
@@ -706,16 +706,16 @@ static int
 deque_del_item(dequeobject *deque, Py_ssize_t i)
 {
     PyObject *item;
+    int rv;
 
     assert (i >= 0 && i < deque->len);
-    if (_deque_rotate(deque, -i) == -1)
+    if (_deque_rotate(deque, -i))
         return -1;
-
     item = deque_popleft(deque, NULL);
+    rv = _deque_rotate(deque, i);
     assert (item != NULL);
     Py_DECREF(item);
-
-    return _deque_rotate(deque, i);
+    return rv;
 }
 
 static int
index 1700afd..96ffa9d 100644 (file)
@@ -642,7 +642,7 @@ CDataType_in_dll(PyObject *type, PyObject *args)
 #ifdef __CYGWIN__
 /* dlerror() isn't very helpful on cygwin */
         PyErr_Format(PyExc_ValueError,
-                     "symbol '%s' not found (%s) ",
+                     "symbol '%s' not found",
                      name);
 #else
         PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
@@ -3393,7 +3393,7 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
 #ifdef __CYGWIN__
 /* dlerror() isn't very helpful on cygwin */
         PyErr_Format(PyExc_AttributeError,
-                     "function '%s' not found (%s) ",
+                     "function '%s' not found",
                      name);
 #else
         PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
@@ -4469,8 +4469,11 @@ Array_subscript(PyObject *_self, PyObject *item)
                                               slicelen);
             }
 
-            dest = (wchar_t *)PyMem_Malloc(
-                                    slicelen * sizeof(wchar_t));
+            dest = PyMem_New(wchar_t, slicelen);
+            if (dest == NULL) {
+                PyErr_NoMemory();
+                return NULL;
+            }
 
             for (cur = start, i = 0; i < slicelen;
                  cur += step, i++) {
@@ -5060,7 +5063,7 @@ Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
     *(void **)self->b_ptr = dst->b_ptr;
 
     /*
-       A Pointer instance must keep the value it points to alive.  So, a
+       A Pointer instance must keep the value it points to alive.  So, a
        pointer instance has b_length set to 2 instead of 1, and we set
        'value' itself as the second item of the b_objects list, additionally.
     */
@@ -5250,7 +5253,7 @@ Pointer_subscript(PyObject *_self, PyObject *item)
                 return PyUnicode_FromWideChar(ptr + start,
                                               len);
             }
-            dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
+            dest = PyMem_New(wchar_t, len);
             if (dest == NULL)
                 return PyErr_NoMemory();
             for (cur = start, i = 0; i < len; cur += step, i++) {
index 64b19ec..dbf9c8e 100644 (file)
@@ -331,10 +331,11 @@ ffi_status ffi_prep_cif_machdep(ffi_cif *cif)
 extern int
 ffi_call_win64(void (*)(char *, extended_cif *), extended_cif *,
                unsigned, unsigned, unsigned *, void (*fn)(void));
-#else
+#elif defined(X86_WIN32)
 extern void
 ffi_call_win32(void (*)(char *, extended_cif *), extended_cif *,
                unsigned, unsigned, unsigned, unsigned *, void (*fn)(void));
+#else
 extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *,
                           unsigned, unsigned, unsigned *, void (*fn)(void));
 #endif
@@ -376,16 +377,9 @@ void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
       ffi_call_win64(ffi_prep_args, &ecif, cif->bytes,
                      cif->flags, ecif.rvalue, fn);
       break;
-#else
-#ifndef X86_WIN32
-    case FFI_SYSV:
-      ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue,
-                    fn);
-      break;
-#else
+#elif defined(X86_WIN32)
     case FFI_SYSV:
     case FFI_MS_CDECL:
-#endif
     case FFI_STDCALL:
       ffi_call_win32(ffi_prep_args, &ecif, cif->abi, cif->bytes, cif->flags,
                     ecif.rvalue, fn);
@@ -419,6 +413,11 @@ void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
                        ecif.rvalue, fn);
       }
       break;
+#else
+    case FFI_SYSV:
+      ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue,
+                    fn);
+      break;
 #endif
     default:
       FFI_ASSERT(0);
@@ -787,28 +786,36 @@ ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *fake_avalue)
   /* If the return value is a struct and we don't have a return */
   /* value address then we need to make one                     */
 
+#ifdef X86_WIN64
+  if (rvalue == NULL
+      && cif->flags == FFI_TYPE_STRUCT
+      && cif->rtype->size != 1 && cif->rtype->size != 2
+      && cif->rtype->size != 4 && cif->rtype->size != 8)
+    {
+      ecif.rvalue = alloca((cif->rtype->size + 0xF) & ~0xF);
+    }
+#else
   if (rvalue == NULL
       && (cif->flags == FFI_TYPE_STRUCT
           || cif->flags == FFI_TYPE_MS_STRUCT))
     {
       ecif.rvalue = alloca(cif->rtype->size);
     }
+#endif
   else
     ecif.rvalue = rvalue;
     
   
   switch (cif->abi) 
     {
-#ifndef X86_WIN32
-    case FFI_SYSV:
-      ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags,
-                    ecif.rvalue, fn);
+#ifdef X86_WIN64
+    case FFI_WIN64:
+      ffi_call_win64(ffi_prep_args_raw, &ecif, cif->bytes,
+                     cif->flags, ecif.rvalue, fn);
       break;
-#else
+#elif defined(X86_WIN32)
     case FFI_SYSV:
     case FFI_MS_CDECL:
-#endif
-#ifndef X86_WIN64
     case FFI_STDCALL:
       ffi_call_win32(ffi_prep_args_raw, &ecif, cif->abi, cif->bytes, cif->flags,
                     ecif.rvalue, fn);
@@ -835,13 +842,18 @@ ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *fake_avalue)
            ++passed_regs;
          }
        if (passed_regs < 2 && abi == FFI_FASTCALL)
-         cif->abi = abi = FFI_THISCALL;
+         abi = FFI_THISCALL;
        if (passed_regs < 1 && abi == FFI_THISCALL)
-         cif->abi = abi = FFI_STDCALL;
+         abi = FFI_STDCALL;
         ffi_call_win32(ffi_prep_args_raw, &ecif, abi, cif->bytes, cif->flags,
                        ecif.rvalue, fn);
       }
       break;
+#else
+    case FFI_SYSV:
+      ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, ecif.rvalue,
+                    fn);
+      break;
 #endif
     default:
       FFI_ASSERT(0);
index 95fa0f5..17b9760 100644 (file)
@@ -80,14 +80,18 @@ PyCStgDict_clone(StgDictObject *dst, StgDictObject *src)
 
     if (src->format) {
         dst->format = PyMem_Malloc(strlen(src->format) + 1);
-        if (dst->format == NULL)
+        if (dst->format == NULL) {
+            PyErr_NoMemory();
             return -1;
+        }
         strcpy(dst->format, src->format);
     }
     if (src->shape) {
         dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
-        if (dst->shape == NULL)
+        if (dst->shape == NULL) {
+            PyErr_NoMemory();
             return -1;
+        }
         memcpy(dst->shape, src->shape,
                sizeof(Py_ssize_t) * src->ndim);
     }
@@ -388,7 +392,7 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
         union_size = 0;
         total_align = align ? align : 1;
         stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
-        stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
+        stgdict->ffi_type_pointer.elements = PyMem_New(ffi_type *, basedict->length + len + 1);
         if (stgdict->ffi_type_pointer.elements == NULL) {
             PyErr_NoMemory();
             return -1;
@@ -406,7 +410,7 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
         union_size = 0;
         total_align = 1;
         stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
-        stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
+        stgdict->ffi_type_pointer.elements = PyMem_New(ffi_type *, len + 1);
         if (stgdict->ffi_type_pointer.elements == NULL) {
             PyErr_NoMemory();
             return -1;
index 6397ba9..2ba92ba 100644 (file)
@@ -132,17 +132,13 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
         Py_DECREF(pto);
         return NULL;
     }
-    if (kw != NULL) {
-        pto->kw = PyDict_Copy(kw);
-        if (pto->kw == NULL) {
-            Py_DECREF(pto);
-            return NULL;
-        }
-    } else {
-        pto->kw = Py_None;
-        Py_INCREF(Py_None);
+    pto->kw = (kw != NULL) ? PyDict_Copy(kw) : PyDict_New();
+    if (pto->kw == NULL) {
+        Py_DECREF(pto);
+        return NULL;
     }
 
+
     pto->weakreflist = NULL;
     pto->dict = NULL;
 
index 30cedb9..d0ddb09 100644 (file)
@@ -35,10 +35,9 @@ cmp_lt(PyObject *x, PyObject *y)
 static int
 _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
 {
-    PyObject *newitem, *parent, *olditem;
+    PyObject *newitem, *parent;
+    Py_ssize_t parentpos, size;
     int cmp;
-    Py_ssize_t parentpos;
-    Py_ssize_t size;
 
     assert(PyList_Check(heap));
     size = PyList_GET_SIZE(heap);
@@ -47,39 +46,28 @@ _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
         return -1;
     }
 
-    newitem = PyList_GET_ITEM(heap, pos);
-    Py_INCREF(newitem);
     /* Follow the path to the root, moving parents down until finding
        a place newitem fits. */
-    while (pos > startpos){
+    newitem = PyList_GET_ITEM(heap, pos);
+    while (pos > startpos) {
         parentpos = (pos - 1) >> 1;
         parent = PyList_GET_ITEM(heap, parentpos);
         cmp = cmp_lt(newitem, parent);
-        if (cmp == -1) {
-            Py_DECREF(newitem);
+        if (cmp == -1)
             return -1;
-        }
         if (size != PyList_GET_SIZE(heap)) {
-            Py_DECREF(newitem);
             PyErr_SetString(PyExc_RuntimeError,
                             "list changed size during iteration");
             return -1;
         }
         if (cmp == 0)
             break;
-        Py_INCREF(parent);
-        olditem = PyList_GET_ITEM(heap, pos);
+        parent = PyList_GET_ITEM(heap, parentpos);
+        newitem = PyList_GET_ITEM(heap, pos);
+        PyList_SET_ITEM(heap, parentpos, newitem);
         PyList_SET_ITEM(heap, pos, parent);
-        Py_DECREF(olditem);
         pos = parentpos;
-        if (size != PyList_GET_SIZE(heap)) {
-            PyErr_SetString(PyExc_RuntimeError,
-                            "list changed size during iteration");
-            return -1;
-        }
     }
-    Py_DECREF(PyList_GET_ITEM(heap, pos));
-    PyList_SET_ITEM(heap, pos, newitem);
     return 0;
 }
 
@@ -87,20 +75,16 @@ static int
 _siftup(PyListObject *heap, Py_ssize_t pos)
 {
     Py_ssize_t startpos, endpos, childpos, rightpos, limit;
+    PyObject *tmp1, *tmp2;
     int cmp;
-    PyObject *newitem, *tmp, *olditem;
-    Py_ssize_t size;
 
     assert(PyList_Check(heap));
-    size = PyList_GET_SIZE(heap);
-    endpos = size;
+    endpos = PyList_GET_SIZE(heap);
     startpos = pos;
     if (pos >= endpos) {
         PyErr_SetString(PyExc_IndexError, "index out of range");
         return -1;
     }
-    newitem = PyList_GET_ITEM(heap, pos);
-    Py_INCREF(newitem);
 
     /* Bubble up the smaller child until hitting a leaf. */
     limit = endpos / 2;          /* smallest pos that has no child */
@@ -112,37 +96,24 @@ _siftup(PyListObject *heap, Py_ssize_t pos)
             cmp = cmp_lt(
                 PyList_GET_ITEM(heap, childpos),
                 PyList_GET_ITEM(heap, rightpos));
-            if (cmp == -1) {
-                Py_DECREF(newitem);
+            if (cmp == -1)
                 return -1;
-            }
             if (cmp == 0)
                 childpos = rightpos;
-        }
-        if (size != PyList_GET_SIZE(heap)) {
-            Py_DECREF(newitem);
-            PyErr_SetString(PyExc_RuntimeError,
-                            "list changed size during iteration");
-            return -1;
+            if (endpos != PyList_GET_SIZE(heap)) {
+                PyErr_SetString(PyExc_RuntimeError,
+                                "list changed size during iteration");
+                return -1;
+            }
         }
         /* Move the smaller child up. */
-        tmp = PyList_GET_ITEM(heap, childpos);
-        Py_INCREF(tmp);
-        olditem = PyList_GET_ITEM(heap, pos);
-        PyList_SET_ITEM(heap, pos, tmp);
-        Py_DECREF(olditem);
+        tmp1 = PyList_GET_ITEM(heap, childpos);
+        tmp2 = PyList_GET_ITEM(heap, pos);
+        PyList_SET_ITEM(heap, childpos, tmp2);
+        PyList_SET_ITEM(heap, pos, tmp1);
         pos = childpos;
-        if (size != PyList_GET_SIZE(heap)) {
-            PyErr_SetString(PyExc_RuntimeError,
-                            "list changed size during iteration");
-            return -1;
-        }
     }
-
-    /* The leaf at pos is empty now.  Put newitem there, and bubble
-       it up to its final resting place (by sifting its parents down). */
-    Py_DECREF(PyList_GET_ITEM(heap, pos));
-    PyList_SET_ITEM(heap, pos, newitem);
+    /* Bubble it up to its final resting place (by sifting its parents down). */
     return _siftdown(heap, startpos, pos);
 }
 
index 29db164..04c4445 100644 (file)
@@ -529,14 +529,8 @@ io_open(PyObject *self, PyObject *args, PyObject *kwds)
         PyObject *exc, *val, *tb, *close_result;
         PyErr_Fetch(&exc, &val, &tb);
         close_result = PyObject_CallMethod(result, "close", NULL);
-        if (close_result != NULL) {
-            Py_DECREF(close_result);
-            PyErr_Restore(exc, val, tb);
-        } else {
-            Py_XDECREF(exc);
-            Py_XDECREF(val);
-            Py_XDECREF(tb);
-        }
+        _PyErr_ReplaceException(exc, val, tb);
+        Py_XDECREF(close_result);
         Py_DECREF(result);
     }
     Py_XDECREF(modeobj);
index 62a350b..b4632ed 100644 (file)
@@ -483,15 +483,8 @@ buffered_close(buffered *self, PyObject *args)
     res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_close, NULL);
 
     if (exc != NULL) {
-        if (res != NULL) {
-            Py_CLEAR(res);
-            PyErr_Restore(exc, val, tb);
-        }
-        else {
-            Py_DECREF(exc);
-            Py_XDECREF(val);
-            Py_XDECREF(tb);
-        }
+        _PyErr_ReplaceException(exc, val, tb);
+        Py_CLEAR(res);
     }
 
 end:
@@ -1222,7 +1215,7 @@ buffered_repr(buffered *self)
 
     nameobj = PyObject_GetAttrString((PyObject *) self, "name");
     if (nameobj == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_AttributeError))
+        if (PyErr_ExceptionMatches(PyExc_Exception))
             PyErr_Clear();
         else
             return NULL;
@@ -2200,12 +2193,25 @@ bufferedrwpair_writable(rwpair *self, PyObject *args)
 static PyObject *
 bufferedrwpair_close(rwpair *self, PyObject *args)
 {
+    PyObject *exc = NULL, *val, *tb;
     PyObject *ret = _forward_call(self->writer, "close", args);
     if (ret == NULL)
-        return NULL;
-    Py_DECREF(ret);
-
-    return _forward_call(self->reader, "close", args);
+        PyErr_Fetch(&exc, &val, &tb);
+    else
+        Py_DECREF(ret);
+    ret = _forward_call(self->reader, "close", args);
+    if (exc != NULL) {
+        if (ret != NULL) {
+            Py_CLEAR(ret);
+            PyErr_Restore(exc, val, tb);
+        }
+        else {
+            Py_DECREF(exc);
+            Py_XDECREF(val);
+            Py_XDECREF(tb);
+        }
+    }
+    return ret;
 }
 
 static PyObject *
index 94f62d0..098aef4 100644 (file)
@@ -101,16 +101,16 @@ internal_close(fileio *self)
 static PyObject *
 fileio_close(fileio *self)
 {
+    PyObject *res;
+    res = PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
+                              "close", "O", self);
     if (!self->closefd) {
         self->fd = -1;
-        Py_RETURN_NONE;
+        return res;
     }
-    errno = internal_close(self);
-    if (errno < 0)
-        return NULL;
-
-    return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
-                               "close", "O", self);
+    if (internal_close(self) < 0)
+        Py_CLEAR(res);
+    return res;
 }
 
 static PyObject *
@@ -217,7 +217,7 @@ fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
     if (fd < 0) {
         if (!PyErr_Occurred()) {
             PyErr_SetString(PyExc_ValueError,
-                            "Negative filedescriptor");
+                            "negative file descriptor");
             return -1;
         }
         PyErr_Clear();
@@ -949,7 +949,7 @@ fileio_isatty(fileio *self)
 PyDoc_STRVAR(fileio_doc,
 "file(name: str[, mode: str]) -> file IO object\n"
 "\n"
-"Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),\n"
+"Open a file.  The mode can be 'r' (default), 'w' or 'a' for reading,\n"
 "writing or appending.  The file will be created if it doesn't exist\n"
 "when opened for writing or appending; it will be truncated when\n"
 "opened for writing.  Add a '+' to the mode to allow simultaneous\n"
@@ -972,22 +972,22 @@ PyDoc_STRVAR(write_doc,
 "write(b: bytes) -> int.  Write bytes b to file, return number written.\n"
 "\n"
 "Only makes one system call, so not all of the data may be written.\n"
-"The number of bytes actually written is returned.");
+"The number of bytes actually written is returned.  In non-blocking mode,\n"
+"returns None if the write would block."
+);
 
 PyDoc_STRVAR(fileno_doc,
-"fileno() -> int. \"file descriptor\".\n"
-"\n"
-"This is needed for lower-level file interfaces, such the fcntl module.");
+"fileno() -> int.  Return the underlying file descriptor (an integer).");
 
 PyDoc_STRVAR(seek_doc,
 "seek(offset: int[, whence: int]) -> int.  Move to new file position\n"
 "and return the file position.\n"
 "\n"
 "Argument offset is a byte count.  Optional argument whence defaults to\n"
-"0 (offset from start of file, offset should be >= 0); other values are 1\n"
-"(move relative to current position, positive or negative), and 2 (move\n"
-"relative to end of file, usually negative, although many platforms allow\n"
-"seeking beyond the end of a file)."
+"SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values\n"
+"are SEEK_CUR or 1 (move relative to current position, positive or negative),\n"
+"and SEEK_END or 2 (move relative to end of file, usually negative, although\n"
+"many platforms allow seeking beyond the end of a file).\n"
 "\n"
 "Note that not all file objects are seekable.");
 
@@ -1001,7 +1001,10 @@ PyDoc_STRVAR(truncate_doc,
 #endif
 
 PyDoc_STRVAR(tell_doc,
-"tell() -> int.  Current file position");
+"tell() -> int.  Current file position.\n"
+"\n"
+"Can raise OSError for non seekable files."
+);
 
 PyDoc_STRVAR(readinto_doc,
 "readinto() -> Same as RawIOBase.readinto().");
@@ -1010,10 +1013,10 @@ PyDoc_STRVAR(close_doc,
 "close() -> None.  Close the file.\n"
 "\n"
 "A closed file cannot be used for further I/O operations.  close() may be\n"
-"called more than once without error.  Changes the fileno to -1.");
+"called more than once without error.");
 
 PyDoc_STRVAR(isatty_doc,
-"isatty() -> bool.  True if the file is connected to a tty device.");
+"isatty() -> bool.  True if the file is connected to a TTY device.");
 
 PyDoc_STRVAR(seekable_doc,
 "seekable() -> bool.  True if file supports random-access.");
@@ -1066,7 +1069,7 @@ get_mode(fileio *self, void *closure)
 static PyGetSetDef fileio_getsetlist[] = {
     {"closed", (getter)get_closed, NULL, "True if the file is closed"},
     {"closefd", (getter)get_closefd, NULL,
-        "True if the file descriptor will be closed"},
+        "True if the file descriptor will be closed by close()."},
     {"mode", (getter)get_mode, NULL, "String giving the file mode"},
     {NULL},
 };
index 6802758..8ac8a4a 100644 (file)
@@ -1152,25 +1152,27 @@ textiowrapper_closed_get(textio *self, void *context);
 
 #define CHECK_INITIALIZED(self) \
     if (self->ok <= 0) { \
-        if (self->detached) { \
-            PyErr_SetString(PyExc_ValueError, \
-                 "underlying buffer has been detached"); \
-        } else {                                   \
-            PyErr_SetString(PyExc_ValueError, \
-                "I/O operation on uninitialized object"); \
-        } \
+        PyErr_SetString(PyExc_ValueError, \
+            "I/O operation on uninitialized object"); \
         return NULL; \
     }
 
-#define CHECK_INITIALIZED_INT(self) \
+#define CHECK_ATTACHED(self) \
+    CHECK_INITIALIZED(self); \
+    if (self->detached) { \
+        PyErr_SetString(PyExc_ValueError, \
+             "underlying buffer has been detached"); \
+        return NULL; \
+    }
+
+#define CHECK_ATTACHED_INT(self) \
     if (self->ok <= 0) { \
-        if (self->detached) { \
-            PyErr_SetString(PyExc_ValueError, \
-                 "underlying buffer has been detached"); \
-        } else {                                   \
-            PyErr_SetString(PyExc_ValueError, \
-                "I/O operation on uninitialized object"); \
-        } \
+        PyErr_SetString(PyExc_ValueError, \
+            "I/O operation on uninitialized object"); \
+        return -1; \
+    } else if (self->detached) { \
+        PyErr_SetString(PyExc_ValueError, \
+             "underlying buffer has been detached"); \
         return -1; \
     }
 
@@ -1179,7 +1181,7 @@ static PyObject *
 textiowrapper_detach(textio *self)
 {
     PyObject *buffer, *res;
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL);
     if (res == NULL)
         return NULL;
@@ -1187,7 +1189,6 @@ textiowrapper_detach(textio *self)
     buffer = self->buffer;
     self->buffer = NULL;
     self->detached = 1;
-    self->ok = 0;
     return buffer;
 }
 
@@ -1244,7 +1245,7 @@ textiowrapper_write(textio *self, PyObject *args)
     int haslf = 0;
     int needflush = 0;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
 
     if (!PyArg_ParseTuple(args, "U:write", &text)) {
         return NULL;
@@ -1486,7 +1487,7 @@ textiowrapper_read(textio *self, PyObject *args)
     Py_ssize_t n = -1;
     PyObject *result = NULL, *chunks = NULL;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
 
     if (!PyArg_ParseTuple(args, "|O&:read", &_PyIO_ConvertSsize_t, &n))
         return NULL;
@@ -1849,7 +1850,7 @@ textiowrapper_readline(textio *self, PyObject *args)
     PyObject *limitobj = NULL;
     Py_ssize_t limit = -1;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     if (!PyArg_ParseTuple(args, "|O:readline", &limitobj)) {
         return NULL;
     }
@@ -2004,7 +2005,7 @@ textiowrapper_seek(textio *self, PyObject *args)
     PyObject *res;
     int cmp;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
 
     if (!PyArg_ParseTuple(args, "O|i:seek", &cookieObj, &whence))
         return NULL;
@@ -2189,7 +2190,7 @@ textiowrapper_tell(textio *self, PyObject *args)
     PyObject *saved_state = NULL;
     char *input, *input_end;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     CHECK_CLOSED(self);
 
     if (!self->seekable) {
@@ -2337,12 +2338,9 @@ textiowrapper_tell(textio *self, PyObject *args)
         PyErr_Fetch(&type, &value, &traceback);
 
         res = PyObject_CallMethod(self->decoder, "setstate", "(O)", saved_state);
+        _PyErr_ReplaceException(type, value, traceback);
         Py_DECREF(saved_state);
-        if (res == NULL)
-            return NULL;
-        Py_DECREF(res);
-
-        PyErr_Restore(type, value, traceback);
+        Py_XDECREF(res);
     }
     return NULL;
 }
@@ -2353,7 +2351,7 @@ textiowrapper_truncate(textio *self, PyObject *args)
     PyObject *pos = Py_None;
     PyObject *res;
 
-    CHECK_INITIALIZED(self)
+    CHECK_ATTACHED(self)
     if (!PyArg_ParseTuple(args, "|O:truncate", &pos)) {
         return NULL;
     }
@@ -2376,7 +2374,7 @@ textiowrapper_repr(textio *self)
 
     nameobj = PyObject_GetAttrString((PyObject *) self, "name");
     if (nameobj == NULL) {
-        if (PyErr_ExceptionMatches(PyExc_AttributeError))
+        if (PyErr_ExceptionMatches(PyExc_Exception))
             PyErr_Clear();
         else
             goto error;
@@ -2408,42 +2406,42 @@ error:
 static PyObject *
 textiowrapper_fileno(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_CallMethod(self->buffer, "fileno", NULL);
 }
 
 static PyObject *
 textiowrapper_seekable(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_CallMethod(self->buffer, "seekable", NULL);
 }
 
 static PyObject *
 textiowrapper_readable(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_CallMethod(self->buffer, "readable", NULL);
 }
 
 static PyObject *
 textiowrapper_writable(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_CallMethod(self->buffer, "writable", NULL);
 }
 
 static PyObject *
 textiowrapper_isatty(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_CallMethod(self->buffer, "isatty", NULL);
 }
 
 static PyObject *
 textiowrapper_flush(textio *self, PyObject *args)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     CHECK_CLOSED(self);
     self->telling = self->seekable;
     if (_textiowrapper_writeflush(self) < 0)
@@ -2456,7 +2454,7 @@ textiowrapper_close(textio *self, PyObject *args)
 {
     PyObject *res;
     int r;
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
 
     res = textiowrapper_closed_get(self, NULL);
     if (res == NULL)
@@ -2479,15 +2477,8 @@ textiowrapper_close(textio *self, PyObject *args)
 
         res = PyObject_CallMethod(self->buffer, "close", NULL);
         if (exc != NULL) {
-            if (res != NULL) {
-                Py_CLEAR(res);
-                PyErr_Restore(exc, val, tb);
-            }
-            else {
-                Py_DECREF(exc);
-                Py_XDECREF(val);
-                Py_XDECREF(tb);
-            }
+            _PyErr_ReplaceException(exc, val, tb);
+            Py_CLEAR(res);
         }
         return res;
     }
@@ -2498,7 +2489,7 @@ textiowrapper_iternext(textio *self)
 {
     PyObject *line;
 
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
 
     self->telling = 0;
     if (Py_TYPE(self) == &PyTextIOWrapper_Type) {
@@ -2534,14 +2525,14 @@ textiowrapper_iternext(textio *self)
 static PyObject *
 textiowrapper_name_get(textio *self, void *context)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_GetAttrString(self->buffer, "name");
 }
 
 static PyObject *
 textiowrapper_closed_get(textio *self, void *context)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyObject_GetAttr(self->buffer, _PyIO_str_closed);
 }
 
@@ -2549,7 +2540,7 @@ static PyObject *
 textiowrapper_newlines_get(textio *self, void *context)
 {
     PyObject *res;
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     if (self->decoder == NULL)
         Py_RETURN_NONE;
     res = PyObject_GetAttr(self->decoder, _PyIO_str_newlines);
@@ -2576,7 +2567,7 @@ textiowrapper_errors_get(textio *self, void *context)
 static PyObject *
 textiowrapper_chunk_size_get(textio *self, void *context)
 {
-    CHECK_INITIALIZED(self);
+    CHECK_ATTACHED(self);
     return PyLong_FromSsize_t(self->chunk_size);
 }
 
@@ -2584,7 +2575,7 @@ static int
 textiowrapper_chunk_size_set(textio *self, PyObject *arg, void *context)
 {
     Py_ssize_t n;
-    CHECK_INITIALIZED_INT(self);
+    CHECK_ATTACHED_INT(self);
     n = PyNumber_AsSsize_t(arg, PyExc_TypeError);
     if (n == -1 && PyErr_Occurred())
         return -1;
index 253a4dc..fe7b098 100644 (file)
@@ -314,7 +314,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
     }
     /* Convert the unicode strings to wchar[]. */
     len1 = PyUnicode_GET_SIZE(os1) + 1;
-    ws1 = PyMem_MALLOC(len1 * sizeof(wchar_t));
+    ws1 = PyMem_NEW(wchar_t, len1);
     if (!ws1) {
         PyErr_NoMemory();
         goto done;
@@ -323,7 +323,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
         goto done;
     ws1[len1 - 1] = 0;
     len2 = PyUnicode_GET_SIZE(os2) + 1;
-    ws2 = PyMem_MALLOC(len2 * sizeof(wchar_t));
+    ws2 = PyMem_NEW(wchar_t, len2);
     if (!ws2) {
         PyErr_NoMemory();
         goto done;
index 0ed196d..79a7a00 100644 (file)
@@ -1192,6 +1192,9 @@ PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, Py
         return NULL;
     }
 
+    if (!_PyArg_NoKeywords(MODULE_NAME ".Connection()", kwargs))
+        return NULL;
+
     if (!PyArg_ParseTuple(args, "O", &sql)) {
         return NULL;
     }
@@ -1242,7 +1245,7 @@ error:
     return (PyObject*)statement;
 }
 
-PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
 {
     PyObject* cursor = 0;
     PyObject* result = 0;
@@ -1271,7 +1274,7 @@ error:
     return cursor;
 }
 
-PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
 {
     PyObject* cursor = 0;
     PyObject* result = 0;
@@ -1300,7 +1303,7 @@ error:
     return cursor;
 }
 
-PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
 {
     PyObject* cursor = 0;
     PyObject* result = 0;
index 898d6c0..b7537e6 100644 (file)
@@ -105,6 +105,11 @@ struct py_ssl_library_code {
 # define HAVE_SNI 0
 #endif
 
+/* ALPN added in OpenSSL 1.0.2 */
+#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
+# define HAVE_ALPN
+#endif
+
 enum py_ssl_error {
     /* these mirror ssl.h */
     PY_SSL_ERROR_NONE,
@@ -205,9 +210,13 @@ typedef struct {
     PyObject_HEAD
     SSL_CTX *ctx;
 #ifdef OPENSSL_NPN_NEGOTIATED
-    char *npn_protocols;
+    unsigned char *npn_protocols;
     int npn_protocols_len;
 #endif
+#ifdef HAVE_ALPN
+    unsigned char *alpn_protocols;
+    int alpn_protocols_len;
+#endif
 #ifndef OPENSSL_NO_TLSEXT
     PyObject *set_hostname;
 #endif
@@ -1408,7 +1417,20 @@ static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
 
     if (out == NULL)
         Py_RETURN_NONE;
-    return PyUnicode_FromStringAndSize((char *) out, outlen);
+    return PyString_FromStringAndSize((char *)out, outlen);
+}
+#endif
+
+#ifdef HAVE_ALPN
+static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
+    const unsigned char *out;
+    unsigned int outlen;
+
+    SSL_get0_alpn_selected(self->ssl, &out, &outlen);
+
+    if (out == NULL)
+        Py_RETURN_NONE;
+    return PyString_FromStringAndSize((char *)out, outlen);
 }
 #endif
 
@@ -1698,26 +1720,6 @@ static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
     BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
     BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
 
-    /* first check if there are bytes ready to be read */
-    PySSL_BEGIN_ALLOW_THREADS
-    count = SSL_pending(self->ssl);
-    PySSL_END_ALLOW_THREADS
-
-    if (!count) {
-        sockstate = check_socket_and_wait_for_timeout(sock, 0);
-        if (sockstate == SOCKET_HAS_TIMED_OUT) {
-            PyErr_SetString(PySSLErrorObject,
-                            "The read operation timed out");
-            goto error;
-        } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
-            PyErr_SetString(PySSLErrorObject,
-                            "Underlying socket too large for select().");
-            goto error;
-        } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
-            count = 0;
-            goto done;
-        }
-    }
     do {
         PySSL_BEGIN_ALLOW_THREADS
         count = SSL_read(self->ssl, mem, len);
@@ -1925,6 +1927,9 @@ static PyMethodDef PySSLMethods[] = {
 #ifdef OPENSSL_NPN_NEGOTIATED
     {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
 #endif
+#ifdef HAVE_ALPN
+    {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
+#endif
     {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
     {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
      PySSL_SSLshutdown_doc},
@@ -2032,6 +2037,9 @@ context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 #ifdef OPENSSL_NPN_NEGOTIATED
     self->npn_protocols = NULL;
 #endif
+#ifdef HAVE_ALPN
+    self->alpn_protocols = NULL;
+#endif
 #ifndef OPENSSL_NO_TLSEXT
     self->set_hostname = NULL;
 #endif
@@ -2064,6 +2072,15 @@ context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
                                    sizeof(SID_CTX));
 #undef SID_CTX
 
+#ifdef X509_V_FLAG_TRUSTED_FIRST
+    {
+        /* Improve trust chain building when cross-signed intermediate
+           certificates are present. See https://bugs.python.org/issue23476. */
+        X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
+        X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
+    }
+#endif
+
     return (PyObject *)self;
 }
 
@@ -2091,7 +2108,10 @@ context_dealloc(PySSLContext *self)
     context_clear(self);
     SSL_CTX_free(self->ctx);
 #ifdef OPENSSL_NPN_NEGOTIATED
-    PyMem_Free(self->npn_protocols);
+    PyMem_FREE(self->npn_protocols);
+#endif
+#ifdef HAVE_ALPN
+    PyMem_FREE(self->alpn_protocols);
 #endif
     Py_TYPE(self)->tp_free(self);
 }
@@ -2118,6 +2138,30 @@ set_ciphers(PySSLContext *self, PyObject *args)
 }
 
 #ifdef OPENSSL_NPN_NEGOTIATED
+static int
+do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
+                      const unsigned char *server_protocols, unsigned int server_protocols_len,
+                      const unsigned char *client_protocols, unsigned int client_protocols_len)
+{
+    int ret;
+    if (client_protocols == NULL) {
+        client_protocols = (unsigned char *)"";
+        client_protocols_len = 0;
+    }
+    if (server_protocols == NULL) {
+        server_protocols = (unsigned char *)"";
+        server_protocols_len = 0;
+    }
+
+    ret = SSL_select_next_proto(out, outlen,
+                                server_protocols, server_protocols_len,
+                                client_protocols, client_protocols_len);
+    if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
+        return SSL_TLSEXT_ERR_NOACK;
+
+    return SSL_TLSEXT_ERR_OK;
+}
+
 /* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
 static int
 _advertiseNPN_cb(SSL *s,
@@ -2127,10 +2171,10 @@ _advertiseNPN_cb(SSL *s,
     PySSLContext *ssl_ctx = (PySSLContext *) args;
 
     if (ssl_ctx->npn_protocols == NULL) {
-        *data = (unsigned char *) "";
+        *data = (unsigned char *)"";
         *len = 0;
     } else {
-        *data = (unsigned char *) ssl_ctx->npn_protocols;
+        *data = ssl_ctx->npn_protocols;
         *len = ssl_ctx->npn_protocols_len;
     }
 
@@ -2143,23 +2187,9 @@ _selectNPN_cb(SSL *s,
               const unsigned char *server, unsigned int server_len,
               void *args)
 {
-    PySSLContext *ssl_ctx = (PySSLContext *) args;
-
-    unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
-    int client_len;
-
-    if (client == NULL) {
-        client = (unsigned char *) "";
-        client_len = 0;
-    } else {
-        client_len = ssl_ctx->npn_protocols_len;
-    }
-
-    SSL_select_next_proto(out, outlen,
-                          server, server_len,
-                          client, client_len);
-
-    return SSL_TLSEXT_ERR_OK;
+    PySSLContext *ctx = (PySSLContext *)args;
+    return do_protocol_selection(0, out, outlen, server, server_len,
+                                 ctx->npn_protocols, ctx->npn_protocols_len);
 }
 #endif
 
@@ -2202,6 +2232,50 @@ _set_npn_protocols(PySSLContext *self, PyObject *args)
 #endif
 }
 
+#ifdef HAVE_ALPN
+static int
+_selectALPN_cb(SSL *s,
+              const unsigned char **out, unsigned char *outlen,
+              const unsigned char *client_protocols, unsigned int client_protocols_len,
+              void *args)
+{
+    PySSLContext *ctx = (PySSLContext *)args;
+    return do_protocol_selection(1, (unsigned char **)out, outlen,
+                                 ctx->alpn_protocols, ctx->alpn_protocols_len,
+                                 client_protocols, client_protocols_len);
+}
+#endif
+
+static PyObject *
+_set_alpn_protocols(PySSLContext *self, PyObject *args)
+{
+#ifdef HAVE_ALPN
+    Py_buffer protos;
+
+    if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
+        return NULL;
+
+    PyMem_FREE(self->alpn_protocols);
+    self->alpn_protocols = PyMem_Malloc(protos.len);
+    if (!self->alpn_protocols)
+        return PyErr_NoMemory();
+    memcpy(self->alpn_protocols, protos.buf, protos.len);
+    self->alpn_protocols_len = protos.len;
+    PyBuffer_Release(&protos);
+
+    if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
+        return PyErr_NoMemory();
+    SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
+
+    PyBuffer_Release(&protos);
+    Py_RETURN_NONE;
+#else
+    PyErr_SetString(PyExc_NotImplementedError,
+                    "The ALPN extension requires OpenSSL 1.0.2 or later.");
+    return NULL;
+#endif
+}
+
 static PyObject *
 get_verify_mode(PySSLContext *self, void *c)
 {
@@ -3188,6 +3262,8 @@ static struct PyMethodDef context_methods[] = {
                        METH_VARARGS | METH_KEYWORDS, NULL},
     {"set_ciphers", (PyCFunction) set_ciphers,
                     METH_VARARGS, NULL},
+    {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
+                           METH_VARARGS, NULL},
     {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
                            METH_VARARGS, NULL},
     {"load_cert_chain", (PyCFunction) load_cert_chain,
@@ -3301,6 +3377,11 @@ Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
 using the ssl() function.");
 
+#endif /* HAVE_OPENSSL_RAND */
+
+
+#ifdef HAVE_RAND_EGD
+
 static PyObject *
 PySSL_RAND_egd(PyObject *self, PyObject *arg)
 {
@@ -3327,7 +3408,7 @@ Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
 Returns number of bytes read.  Raises SSLError if connection to EGD\n\
 fails or if it does not provide enough data to seed PRNG.");
 
-#endif /* HAVE_OPENSSL_RAND */
+#endif /* HAVE_RAND_EGD */
 
 
 PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
@@ -3564,7 +3645,7 @@ PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
     PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
     PyObject *result = NULL;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
                                      kwlist, &store_name)) {
         return NULL;
     }
@@ -3652,7 +3733,7 @@ PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
     PyObject *crl = NULL, *enc = NULL, *tup = NULL;
     PyObject *result = NULL;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
                                      kwlist, &store_name)) {
         return NULL;
     }
@@ -3720,11 +3801,13 @@ static PyMethodDef PySSL_methods[] = {
 #ifdef HAVE_OPENSSL_RAND
     {"RAND_add",            PySSL_RAND_add, METH_VARARGS,
      PySSL_RAND_add_doc},
-    {"RAND_egd",            PySSL_RAND_egd, METH_VARARGS,
-     PySSL_RAND_egd_doc},
     {"RAND_status",         (PyCFunction)PySSL_RAND_status, METH_NOARGS,
      PySSL_RAND_status_doc},
 #endif
+#ifdef HAVE_RAND_EGD
+    {"RAND_egd",            PySSL_RAND_egd, METH_VARARGS,
+     PySSL_RAND_egd_doc},
+#endif
     {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
      METH_NOARGS, PySSL_get_default_verify_paths_doc},
 #ifdef _MSC_VER
@@ -3797,10 +3880,11 @@ static int _setup_ssl_threads(void) {
 
     if (_ssl_locks == NULL) {
         _ssl_locks_count = CRYPTO_num_locks();
-        _ssl_locks = (PyThread_type_lock *)
-            PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
-        if (_ssl_locks == NULL)
+        _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
+        if (_ssl_locks == NULL) {
+            PyErr_NoMemory();
             return 0;
+        }
         memset(_ssl_locks, 0,
                sizeof(PyThread_type_lock) * _ssl_locks_count);
         for (i = 0;  i < _ssl_locks_count;  i++) {
@@ -3968,6 +4052,10 @@ init_ssl(void)
                             X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
     PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
                             X509_V_FLAG_X509_STRICT);
+#ifdef X509_V_FLAG_TRUSTED_FIRST
+    PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
+                            X509_V_FLAG_TRUSTED_FIRST);
+#endif
 
     /* Alert Descriptions from ssl.h */
     /* note RESERVED constants no longer intended for use have been removed */
@@ -4093,6 +4181,14 @@ init_ssl(void)
     Py_INCREF(r);
     PyModule_AddObject(m, "HAS_NPN", r);
 
+#ifdef HAVE_ALPN
+    r = Py_True;
+#else
+    r = Py_False;
+#endif
+    Py_INCREF(r);
+    PyModule_AddObject(m, "HAS_ALPN", r);
+
     /* Mappings for error codes */
     err_codes_to_names = PyDict_New();
     err_names_to_codes = PyDict_New();
index 81a8d7b..85165b9 100644 (file)
@@ -1,5 +1,5 @@
 /* File generated by Tools/ssl/make_ssl_data.py */
-/* Generated on 2012-05-16T23:56:40.981382 */
+/* Generated on 2015-01-17T20:33:43.377453 */
 
 static struct py_ssl_library_code library_codes[] = {
     {"PEM", ERR_LIB_PEM},
@@ -179,6 +179,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"BAD_CHECKSUM", ERR_LIB_SSL, 104},
   #endif
+  #ifdef SSL_R_BAD_DATA
+    {"BAD_DATA", ERR_LIB_SSL, SSL_R_BAD_DATA},
+  #else
+    {"BAD_DATA", ERR_LIB_SSL, 390},
+  #endif
   #ifdef SSL_R_BAD_DATA_RETURNED_BY_CALLBACK
     {"BAD_DATA_RETURNED_BY_CALLBACK", ERR_LIB_SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK},
   #else
@@ -309,6 +314,46 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"BAD_SIGNATURE", ERR_LIB_SSL, 123},
   #endif
+  #ifdef SSL_R_BAD_SRP_A_LENGTH
+    {"BAD_SRP_A_LENGTH", ERR_LIB_SSL, SSL_R_BAD_SRP_A_LENGTH},
+  #else
+    {"BAD_SRP_A_LENGTH", ERR_LIB_SSL, 347},
+  #endif
+  #ifdef SSL_R_BAD_SRP_B_LENGTH
+    {"BAD_SRP_B_LENGTH", ERR_LIB_SSL, SSL_R_BAD_SRP_B_LENGTH},
+  #else
+    {"BAD_SRP_B_LENGTH", ERR_LIB_SSL, 348},
+  #endif
+  #ifdef SSL_R_BAD_SRP_G_LENGTH
+    {"BAD_SRP_G_LENGTH", ERR_LIB_SSL, SSL_R_BAD_SRP_G_LENGTH},
+  #else
+    {"BAD_SRP_G_LENGTH", ERR_LIB_SSL, 349},
+  #endif
+  #ifdef SSL_R_BAD_SRP_N_LENGTH
+    {"BAD_SRP_N_LENGTH", ERR_LIB_SSL, SSL_R_BAD_SRP_N_LENGTH},
+  #else
+    {"BAD_SRP_N_LENGTH", ERR_LIB_SSL, 350},
+  #endif
+  #ifdef SSL_R_BAD_SRP_PARAMETERS
+    {"BAD_SRP_PARAMETERS", ERR_LIB_SSL, SSL_R_BAD_SRP_PARAMETERS},
+  #else
+    {"BAD_SRP_PARAMETERS", ERR_LIB_SSL, 371},
+  #endif
+  #ifdef SSL_R_BAD_SRP_S_LENGTH
+    {"BAD_SRP_S_LENGTH", ERR_LIB_SSL, SSL_R_BAD_SRP_S_LENGTH},
+  #else
+    {"BAD_SRP_S_LENGTH", ERR_LIB_SSL, 351},
+  #endif
+  #ifdef SSL_R_BAD_SRTP_MKI_VALUE
+    {"BAD_SRTP_MKI_VALUE", ERR_LIB_SSL, SSL_R_BAD_SRTP_MKI_VALUE},
+  #else
+    {"BAD_SRTP_MKI_VALUE", ERR_LIB_SSL, 352},
+  #endif
+  #ifdef SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST
+    {"BAD_SRTP_PROTECTION_PROFILE_LIST", ERR_LIB_SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST},
+  #else
+    {"BAD_SRTP_PROTECTION_PROFILE_LIST", ERR_LIB_SSL, 353},
+  #endif
   #ifdef SSL_R_BAD_SSL_FILETYPE
     {"BAD_SSL_FILETYPE", ERR_LIB_SSL, SSL_R_BAD_SSL_FILETYPE},
   #else
@@ -324,6 +369,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"BAD_STATE", ERR_LIB_SSL, 126},
   #endif
+  #ifdef SSL_R_BAD_VALUE
+    {"BAD_VALUE", ERR_LIB_SSL, SSL_R_BAD_VALUE},
+  #else
+    {"BAD_VALUE", ERR_LIB_SSL, 384},
+  #endif
   #ifdef SSL_R_BAD_WRITE_RETRY
     {"BAD_WRITE_RETRY", ERR_LIB_SSL, SSL_R_BAD_WRITE_RETRY},
   #else
@@ -354,6 +404,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"CA_DN_TOO_LONG", ERR_LIB_SSL, 132},
   #endif
+  #ifdef SSL_R_CA_KEY_TOO_SMALL
+    {"CA_KEY_TOO_SMALL", ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL},
+  #else
+    {"CA_KEY_TOO_SMALL", ERR_LIB_SSL, 397},
+  #endif
+  #ifdef SSL_R_CA_MD_TOO_WEAK
+    {"CA_MD_TOO_WEAK", ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK},
+  #else
+    {"CA_MD_TOO_WEAK", ERR_LIB_SSL, 398},
+  #endif
   #ifdef SSL_R_CCS_RECEIVED_EARLY
     {"CCS_RECEIVED_EARLY", ERR_LIB_SSL, SSL_R_CCS_RECEIVED_EARLY},
   #else
@@ -364,6 +424,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"CERTIFICATE_VERIFY_FAILED", ERR_LIB_SSL, 134},
   #endif
+  #ifdef SSL_R_CERT_CB_ERROR
+    {"CERT_CB_ERROR", ERR_LIB_SSL, SSL_R_CERT_CB_ERROR},
+  #else
+    {"CERT_CB_ERROR", ERR_LIB_SSL, 377},
+  #endif
   #ifdef SSL_R_CERT_LENGTH_MISMATCH
     {"CERT_LENGTH_MISMATCH", ERR_LIB_SSL, SSL_R_CERT_LENGTH_MISMATCH},
   #else
@@ -454,6 +519,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"DECRYPTION_FAILED_OR_BAD_RECORD_MAC", ERR_LIB_SSL, 281},
   #endif
+  #ifdef SSL_R_DH_KEY_TOO_SMALL
+    {"DH_KEY_TOO_SMALL", ERR_LIB_SSL, SSL_R_DH_KEY_TOO_SMALL},
+  #else
+    {"DH_KEY_TOO_SMALL", ERR_LIB_SSL, 394},
+  #endif
   #ifdef SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG
     {"DH_PUBLIC_VALUE_LENGTH_IS_WRONG", ERR_LIB_SSL, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG},
   #else
@@ -494,11 +564,26 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE", ERR_LIB_SSL, 323},
   #endif
+  #ifdef SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE
+    {"ECDH_REQUIRED_FOR_SUITEB_MODE", ERR_LIB_SSL, SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE},
+  #else
+    {"ECDH_REQUIRED_FOR_SUITEB_MODE", ERR_LIB_SSL, 374},
+  #endif
   #ifdef SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER
     {"ECGROUP_TOO_LARGE_FOR_CIPHER", ERR_LIB_SSL, SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER},
   #else
     {"ECGROUP_TOO_LARGE_FOR_CIPHER", ERR_LIB_SSL, 310},
   #endif
+  #ifdef SSL_R_EE_KEY_TOO_SMALL
+    {"EE_KEY_TOO_SMALL", ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL},
+  #else
+    {"EE_KEY_TOO_SMALL", ERR_LIB_SSL, 399},
+  #endif
+  #ifdef SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST
+    {"EMPTY_SRTP_PROTECTION_PROFILE_LIST", ERR_LIB_SSL, SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST},
+  #else
+    {"EMPTY_SRTP_PROTECTION_PROFILE_LIST", ERR_LIB_SSL, 354},
+  #endif
   #ifdef SSL_R_ENCRYPTED_LENGTH_TOO_LONG
     {"ENCRYPTED_LENGTH_TOO_LONG", ERR_LIB_SSL, SSL_R_ENCRYPTED_LENGTH_TOO_LONG},
   #else
@@ -529,6 +614,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"GOT_A_FIN_BEFORE_A_CCS", ERR_LIB_SSL, 154},
   #endif
+  #ifdef SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS
+    {"GOT_NEXT_PROTO_BEFORE_A_CCS", ERR_LIB_SSL, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS},
+  #else
+    {"GOT_NEXT_PROTO_BEFORE_A_CCS", ERR_LIB_SSL, 355},
+  #endif
+  #ifdef SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION
+    {"GOT_NEXT_PROTO_WITHOUT_EXTENSION", ERR_LIB_SSL, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION},
+  #else
+    {"GOT_NEXT_PROTO_WITHOUT_EXTENSION", ERR_LIB_SSL, 356},
+  #endif
   #ifdef SSL_R_HTTPS_PROXY_REQUEST
     {"HTTPS_PROXY_REQUEST", ERR_LIB_SSL, SSL_R_HTTPS_PROXY_REQUEST},
   #else
@@ -544,6 +639,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"ILLEGAL_PADDING", ERR_LIB_SSL, 283},
   #endif
+  #ifdef SSL_R_ILLEGAL_SUITEB_DIGEST
+    {"ILLEGAL_SUITEB_DIGEST", ERR_LIB_SSL, SSL_R_ILLEGAL_SUITEB_DIGEST},
+  #else
+    {"ILLEGAL_SUITEB_DIGEST", ERR_LIB_SSL, 380},
+  #endif
+  #ifdef SSL_R_INAPPROPRIATE_FALLBACK
+    {"INAPPROPRIATE_FALLBACK", ERR_LIB_SSL, SSL_R_INAPPROPRIATE_FALLBACK},
+  #else
+    {"INAPPROPRIATE_FALLBACK", ERR_LIB_SSL, 373},
+  #endif
   #ifdef SSL_R_INCONSISTENT_COMPRESSION
     {"INCONSISTENT_COMPRESSION", ERR_LIB_SSL, SSL_R_INCONSISTENT_COMPRESSION},
   #else
@@ -564,11 +669,26 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"INVALID_COMPRESSION_ALGORITHM", ERR_LIB_SSL, 341},
   #endif
+  #ifdef SSL_R_INVALID_NULL_CMD_NAME
+    {"INVALID_NULL_CMD_NAME", ERR_LIB_SSL, SSL_R_INVALID_NULL_CMD_NAME},
+  #else
+    {"INVALID_NULL_CMD_NAME", ERR_LIB_SSL, 385},
+  #endif
   #ifdef SSL_R_INVALID_PURPOSE
     {"INVALID_PURPOSE", ERR_LIB_SSL, SSL_R_INVALID_PURPOSE},
   #else
     {"INVALID_PURPOSE", ERR_LIB_SSL, 278},
   #endif
+  #ifdef SSL_R_INVALID_SERVERINFO_DATA
+    {"INVALID_SERVERINFO_DATA", ERR_LIB_SSL, SSL_R_INVALID_SERVERINFO_DATA},
+  #else
+    {"INVALID_SERVERINFO_DATA", ERR_LIB_SSL, 388},
+  #endif
+  #ifdef SSL_R_INVALID_SRP_USERNAME
+    {"INVALID_SRP_USERNAME", ERR_LIB_SSL, SSL_R_INVALID_SRP_USERNAME},
+  #else
+    {"INVALID_SRP_USERNAME", ERR_LIB_SSL, 357},
+  #endif
   #ifdef SSL_R_INVALID_STATUS_RESPONSE
     {"INVALID_STATUS_RESPONSE", ERR_LIB_SSL, SSL_R_INVALID_STATUS_RESPONSE},
   #else
@@ -689,6 +809,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"MISSING_DSA_SIGNING_CERT", ERR_LIB_SSL, 165},
   #endif
+  #ifdef SSL_R_MISSING_ECDH_CERT
+    {"MISSING_ECDH_CERT", ERR_LIB_SSL, SSL_R_MISSING_ECDH_CERT},
+  #else
+    {"MISSING_ECDH_CERT", ERR_LIB_SSL, 382},
+  #endif
+  #ifdef SSL_R_MISSING_ECDSA_SIGNING_CERT
+    {"MISSING_ECDSA_SIGNING_CERT", ERR_LIB_SSL, SSL_R_MISSING_ECDSA_SIGNING_CERT},
+  #else
+    {"MISSING_ECDSA_SIGNING_CERT", ERR_LIB_SSL, 381},
+  #endif
   #ifdef SSL_R_MISSING_EXPORT_TMP_DH_KEY
     {"MISSING_EXPORT_TMP_DH_KEY", ERR_LIB_SSL, SSL_R_MISSING_EXPORT_TMP_DH_KEY},
   #else
@@ -714,6 +844,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"MISSING_RSA_SIGNING_CERT", ERR_LIB_SSL, 170},
   #endif
+  #ifdef SSL_R_MISSING_SRP_PARAM
+    {"MISSING_SRP_PARAM", ERR_LIB_SSL, SSL_R_MISSING_SRP_PARAM},
+  #else
+    {"MISSING_SRP_PARAM", ERR_LIB_SSL, 358},
+  #endif
   #ifdef SSL_R_MISSING_TMP_DH_KEY
     {"MISSING_TMP_DH_KEY", ERR_LIB_SSL, SSL_R_MISSING_TMP_DH_KEY},
   #else
@@ -739,6 +874,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"MISSING_VERIFY_MESSAGE", ERR_LIB_SSL, 174},
   #endif
+  #ifdef SSL_R_MULTIPLE_SGC_RESTARTS
+    {"MULTIPLE_SGC_RESTARTS", ERR_LIB_SSL, SSL_R_MULTIPLE_SGC_RESTARTS},
+  #else
+    {"MULTIPLE_SGC_RESTARTS", ERR_LIB_SSL, 346},
+  #endif
   #ifdef SSL_R_NON_SSLV2_INITIAL_PACKET
     {"NON_SSLV2_INITIAL_PACKET", ERR_LIB_SSL, SSL_R_NON_SSLV2_INITIAL_PACKET},
   #else
@@ -819,6 +959,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"NO_METHOD_SPECIFIED", ERR_LIB_SSL, 188},
   #endif
+  #ifdef SSL_R_NO_PEM_EXTENSIONS
+    {"NO_PEM_EXTENSIONS", ERR_LIB_SSL, SSL_R_NO_PEM_EXTENSIONS},
+  #else
+    {"NO_PEM_EXTENSIONS", ERR_LIB_SSL, 389},
+  #endif
   #ifdef SSL_R_NO_PRIVATEKEY
     {"NO_PRIVATEKEY", ERR_LIB_SSL, SSL_R_NO_PRIVATEKEY},
   #else
@@ -854,6 +999,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"NO_SHARED_CIPHER", ERR_LIB_SSL, 193},
   #endif
+  #ifdef SSL_R_NO_SHARED_SIGATURE_ALGORITHMS
+    {"NO_SHARED_SIGATURE_ALGORITHMS", ERR_LIB_SSL, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS},
+  #else
+    {"NO_SHARED_SIGATURE_ALGORITHMS", ERR_LIB_SSL, 376},
+  #endif
+  #ifdef SSL_R_NO_SRTP_PROFILES
+    {"NO_SRTP_PROFILES", ERR_LIB_SSL, SSL_R_NO_SRTP_PROFILES},
+  #else
+    {"NO_SRTP_PROFILES", ERR_LIB_SSL, 359},
+  #endif
   #ifdef SSL_R_NO_VERIFY_CALLBACK
     {"NO_VERIFY_CALLBACK", ERR_LIB_SSL, SSL_R_NO_VERIFY_CALLBACK},
   #else
@@ -879,6 +1034,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED", ERR_LIB_SSL, 344},
   #endif
+  #ifdef SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE
+    {"ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE", ERR_LIB_SSL, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE},
+  #else
+    {"ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE", ERR_LIB_SSL, 387},
+  #endif
+  #ifdef SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE
+    {"ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE", ERR_LIB_SSL, SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE},
+  #else
+    {"ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE", ERR_LIB_SSL, 379},
+  #endif
   #ifdef SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE
     {"ONLY_TLS_ALLOWED_IN_FIPS_MODE", ERR_LIB_SSL, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE},
   #else
@@ -934,6 +1099,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE", ERR_LIB_SSL, 204},
   #endif
+  #ifdef SSL_R_PEM_NAME_BAD_PREFIX
+    {"PEM_NAME_BAD_PREFIX", ERR_LIB_SSL, SSL_R_PEM_NAME_BAD_PREFIX},
+  #else
+    {"PEM_NAME_BAD_PREFIX", ERR_LIB_SSL, 391},
+  #endif
+  #ifdef SSL_R_PEM_NAME_TOO_SHORT
+    {"PEM_NAME_TOO_SHORT", ERR_LIB_SSL, SSL_R_PEM_NAME_TOO_SHORT},
+  #else
+    {"PEM_NAME_TOO_SHORT", ERR_LIB_SSL, 392},
+  #endif
   #ifdef SSL_R_PRE_MAC_LENGTH_TOO_LONG
     {"PRE_MAC_LENGTH_TOO_LONG", ERR_LIB_SSL, SSL_R_PRE_MAC_LENGTH_TOO_LONG},
   #else
@@ -1069,11 +1244,36 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"SHORT_READ", ERR_LIB_SSL, 219},
   #endif
+  #ifdef SSL_R_SIGNATURE_ALGORITHMS_ERROR
+    {"SIGNATURE_ALGORITHMS_ERROR", ERR_LIB_SSL, SSL_R_SIGNATURE_ALGORITHMS_ERROR},
+  #else
+    {"SIGNATURE_ALGORITHMS_ERROR", ERR_LIB_SSL, 360},
+  #endif
   #ifdef SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE
     {"SIGNATURE_FOR_NON_SIGNING_CERTIFICATE", ERR_LIB_SSL, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE},
   #else
     {"SIGNATURE_FOR_NON_SIGNING_CERTIFICATE", ERR_LIB_SSL, 220},
   #endif
+  #ifdef SSL_R_SRP_A_CALC
+    {"SRP_A_CALC", ERR_LIB_SSL, SSL_R_SRP_A_CALC},
+  #else
+    {"SRP_A_CALC", ERR_LIB_SSL, 361},
+  #endif
+  #ifdef SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES
+    {"SRTP_COULD_NOT_ALLOCATE_PROFILES", ERR_LIB_SSL, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES},
+  #else
+    {"SRTP_COULD_NOT_ALLOCATE_PROFILES", ERR_LIB_SSL, 362},
+  #endif
+  #ifdef SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG
+    {"SRTP_PROTECTION_PROFILE_LIST_TOO_LONG", ERR_LIB_SSL, SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG},
+  #else
+    {"SRTP_PROTECTION_PROFILE_LIST_TOO_LONG", ERR_LIB_SSL, 363},
+  #endif
+  #ifdef SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE
+    {"SRTP_UNKNOWN_PROTECTION_PROFILE", ERR_LIB_SSL, SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE},
+  #else
+    {"SRTP_UNKNOWN_PROTECTION_PROFILE", ERR_LIB_SSL, 364},
+  #endif
   #ifdef SSL_R_SSL23_DOING_SESSION_ID_REUSE
     {"SSL23_DOING_SESSION_ID_REUSE", ERR_LIB_SSL, SSL_R_SSL23_DOING_SESSION_ID_REUSE},
   #else
@@ -1179,6 +1379,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"SSL_LIBRARY_HAS_NO_CIPHERS", ERR_LIB_SSL, 230},
   #endif
+  #ifdef SSL_R_SSL_NEGATIVE_LENGTH
+    {"SSL_NEGATIVE_LENGTH", ERR_LIB_SSL, SSL_R_SSL_NEGATIVE_LENGTH},
+  #else
+    {"SSL_NEGATIVE_LENGTH", ERR_LIB_SSL, 372},
+  #endif
   #ifdef SSL_R_SSL_SESSION_ID_CALLBACK_FAILED
     {"SSL_SESSION_ID_CALLBACK_FAILED", ERR_LIB_SSL, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED},
   #else
@@ -1229,6 +1434,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"TLSV1_ALERT_EXPORT_RESTRICTION", ERR_LIB_SSL, 1060},
   #endif
+  #ifdef SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK
+    {"TLSV1_ALERT_INAPPROPRIATE_FALLBACK", ERR_LIB_SSL, SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK},
+  #else
+    {"TLSV1_ALERT_INAPPROPRIATE_FALLBACK", ERR_LIB_SSL, 1086},
+  #endif
   #ifdef SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY
     {"TLSV1_ALERT_INSUFFICIENT_SECURITY", ERR_LIB_SSL, SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY},
   #else
@@ -1294,6 +1504,21 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER", ERR_LIB_SSL, 232},
   #endif
+  #ifdef SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT
+    {"TLS_HEARTBEAT_PEER_DOESNT_ACCEPT", ERR_LIB_SSL, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT},
+  #else
+    {"TLS_HEARTBEAT_PEER_DOESNT_ACCEPT", ERR_LIB_SSL, 365},
+  #endif
+  #ifdef SSL_R_TLS_HEARTBEAT_PENDING
+    {"TLS_HEARTBEAT_PENDING", ERR_LIB_SSL, SSL_R_TLS_HEARTBEAT_PENDING},
+  #else
+    {"TLS_HEARTBEAT_PENDING", ERR_LIB_SSL, 366},
+  #endif
+  #ifdef SSL_R_TLS_ILLEGAL_EXPORTER_LABEL
+    {"TLS_ILLEGAL_EXPORTER_LABEL", ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL},
+  #else
+    {"TLS_ILLEGAL_EXPORTER_LABEL", ERR_LIB_SSL, 367},
+  #endif
   #ifdef SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST
     {"TLS_INVALID_ECPOINTFORMAT_LIST", ERR_LIB_SSL, SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST},
   #else
@@ -1399,6 +1624,16 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"UNKNOWN_CIPHER_TYPE", ERR_LIB_SSL, 249},
   #endif
+  #ifdef SSL_R_UNKNOWN_CMD_NAME
+    {"UNKNOWN_CMD_NAME", ERR_LIB_SSL, SSL_R_UNKNOWN_CMD_NAME},
+  #else
+    {"UNKNOWN_CMD_NAME", ERR_LIB_SSL, 386},
+  #endif
+  #ifdef SSL_R_UNKNOWN_DIGEST
+    {"UNKNOWN_DIGEST", ERR_LIB_SSL, SSL_R_UNKNOWN_DIGEST},
+  #else
+    {"UNKNOWN_DIGEST", ERR_LIB_SSL, 368},
+  #endif
   #ifdef SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE
     {"UNKNOWN_KEY_EXCHANGE_TYPE", ERR_LIB_SSL, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE},
   #else
@@ -1469,16 +1704,36 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"UNSUPPORTED_STATUS_TYPE", ERR_LIB_SSL, 329},
   #endif
+  #ifdef SSL_R_USE_SRTP_NOT_NEGOTIATED
+    {"USE_SRTP_NOT_NEGOTIATED", ERR_LIB_SSL, SSL_R_USE_SRTP_NOT_NEGOTIATED},
+  #else
+    {"USE_SRTP_NOT_NEGOTIATED", ERR_LIB_SSL, 369},
+  #endif
+  #ifdef SSL_R_VERSION_TOO_LOW
+    {"VERSION_TOO_LOW", ERR_LIB_SSL, SSL_R_VERSION_TOO_LOW},
+  #else
+    {"VERSION_TOO_LOW", ERR_LIB_SSL, 396},
+  #endif
   #ifdef SSL_R_WRITE_BIO_NOT_SET
     {"WRITE_BIO_NOT_SET", ERR_LIB_SSL, SSL_R_WRITE_BIO_NOT_SET},
   #else
     {"WRITE_BIO_NOT_SET", ERR_LIB_SSL, 260},
   #endif
+  #ifdef SSL_R_WRONG_CERTIFICATE_TYPE
+    {"WRONG_CERTIFICATE_TYPE", ERR_LIB_SSL, SSL_R_WRONG_CERTIFICATE_TYPE},
+  #else
+    {"WRONG_CERTIFICATE_TYPE", ERR_LIB_SSL, 383},
+  #endif
   #ifdef SSL_R_WRONG_CIPHER_RETURNED
     {"WRONG_CIPHER_RETURNED", ERR_LIB_SSL, SSL_R_WRONG_CIPHER_RETURNED},
   #else
     {"WRONG_CIPHER_RETURNED", ERR_LIB_SSL, 261},
   #endif
+  #ifdef SSL_R_WRONG_CURVE
+    {"WRONG_CURVE", ERR_LIB_SSL, SSL_R_WRONG_CURVE},
+  #else
+    {"WRONG_CURVE", ERR_LIB_SSL, 378},
+  #endif
   #ifdef SSL_R_WRONG_MESSAGE_TYPE
     {"WRONG_MESSAGE_TYPE", ERR_LIB_SSL, SSL_R_WRONG_MESSAGE_TYPE},
   #else
@@ -1499,6 +1754,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"WRONG_SIGNATURE_SIZE", ERR_LIB_SSL, 265},
   #endif
+  #ifdef SSL_R_WRONG_SIGNATURE_TYPE
+    {"WRONG_SIGNATURE_TYPE", ERR_LIB_SSL, SSL_R_WRONG_SIGNATURE_TYPE},
+  #else
+    {"WRONG_SIGNATURE_TYPE", ERR_LIB_SSL, 370},
+  #endif
   #ifdef SSL_R_WRONG_SSL_VERSION
     {"WRONG_SSL_VERSION", ERR_LIB_SSL, SSL_R_WRONG_SSL_VERSION},
   #else
@@ -1519,6 +1779,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"X509_VERIFICATION_SETUP_PROBLEMS", ERR_LIB_SSL, 269},
   #endif
+  #ifdef X509_R_AKID_MISMATCH
+    {"AKID_MISMATCH", ERR_LIB_X509, X509_R_AKID_MISMATCH},
+  #else
+    {"AKID_MISMATCH", ERR_LIB_X509, 110},
+  #endif
   #ifdef X509_R_BAD_X509_FILETYPE
     {"BAD_X509_FILETYPE", ERR_LIB_X509, X509_R_BAD_X509_FILETYPE},
   #else
@@ -1539,11 +1804,26 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"CERT_ALREADY_IN_HASH_TABLE", ERR_LIB_X509, 101},
   #endif
+  #ifdef X509_R_CRL_ALREADY_DELTA
+    {"CRL_ALREADY_DELTA", ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA},
+  #else
+    {"CRL_ALREADY_DELTA", ERR_LIB_X509, 127},
+  #endif
+  #ifdef X509_R_CRL_VERIFY_FAILURE
+    {"CRL_VERIFY_FAILURE", ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE},
+  #else
+    {"CRL_VERIFY_FAILURE", ERR_LIB_X509, 131},
+  #endif
   #ifdef X509_R_ERR_ASN1_LIB
     {"ERR_ASN1_LIB", ERR_LIB_X509, X509_R_ERR_ASN1_LIB},
   #else
     {"ERR_ASN1_LIB", ERR_LIB_X509, 102},
   #endif
+  #ifdef X509_R_IDP_MISMATCH
+    {"IDP_MISMATCH", ERR_LIB_X509, X509_R_IDP_MISMATCH},
+  #else
+    {"IDP_MISMATCH", ERR_LIB_X509, 128},
+  #endif
   #ifdef X509_R_INVALID_DIRECTORY
     {"INVALID_DIRECTORY", ERR_LIB_X509, X509_R_INVALID_DIRECTORY},
   #else
@@ -1559,6 +1839,11 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"INVALID_TRUST", ERR_LIB_X509, 123},
   #endif
+  #ifdef X509_R_ISSUER_MISMATCH
+    {"ISSUER_MISMATCH", ERR_LIB_X509, X509_R_ISSUER_MISMATCH},
+  #else
+    {"ISSUER_MISMATCH", ERR_LIB_X509, 129},
+  #endif
   #ifdef X509_R_KEY_TYPE_MISMATCH
     {"KEY_TYPE_MISMATCH", ERR_LIB_X509, X509_R_KEY_TYPE_MISMATCH},
   #else
@@ -1584,11 +1869,21 @@ static struct py_ssl_error_code error_codes[] = {
   #else
     {"METHOD_NOT_SUPPORTED", ERR_LIB_X509, 124},
   #endif
+  #ifdef X509_R_NEWER_CRL_NOT_NEWER
+    {"NEWER_CRL_NOT_NEWER", ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER},
+  #else
+    {"NEWER_CRL_NOT_NEWER", ERR_LIB_X509, 132},
+  #endif
   #ifdef X509_R_NO_CERT_SET_FOR_US_TO_VERIFY
     {"NO_CERT_SET_FOR_US_TO_VERIFY", ERR_LIB_X509, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY},
   #else
     {"NO_CERT_SET_FOR_US_TO_VERIFY", ERR_LIB_X509, 105},
   #endif
+  #ifdef X509_R_NO_CRL_NUMBER
+    {"NO_CRL_NUMBER", ERR_LIB_X509, X509_R_NO_CRL_NUMBER},
+  #else
+    {"NO_CRL_NUMBER", ERR_LIB_X509, 130},
+  #endif
   #ifdef X509_R_PUBLIC_KEY_DECODE_ERROR
     {"PUBLIC_KEY_DECODE_ERROR", ERR_LIB_X509, X509_R_PUBLIC_KEY_DECODE_ERROR},
   #else
index f035847..bca7a2e 100644 (file)
@@ -1657,8 +1657,8 @@ static PyObject *
 s_pack_into(PyObject *self, PyObject *args)
 {
     PyStructObject *soself;
-    char *buffer;
-    Py_ssize_t buffer_len, offset;
+    Py_buffer buf;
+    Py_ssize_t offset;
 
     /* Validate arguments.  +1 is for the first arg as buffer. */
     soself = (PyStructObject *)self;
@@ -1683,33 +1683,35 @@ s_pack_into(PyObject *self, PyObject *args)
     }
 
     /* Extract a writable memory buffer from the first argument */
-    if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
-                                                            (void**)&buffer, &buffer_len) == -1 ) {
+    if (!PyArg_Parse(PyTuple_GET_ITEM(args, 0), "w*", &buf))
         return NULL;
-    }
-    assert( buffer_len >= 0 );
 
     /* Extract the offset from the first argument */
     offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
-    if (offset == -1 && PyErr_Occurred())
+    if (offset == -1 && PyErr_Occurred()) {
+        PyBuffer_Release(&buf);
         return NULL;
+    }
 
     /* Support negative offsets. */
     if (offset < 0)
-        offset += buffer_len;
+        offset += buf.len;
 
     /* Check boundaries */
-    if (offset < 0 || (buffer_len - offset) < soself->s_size) {
+    if (offset < 0 || (buf.len - offset) < soself->s_size) {
         PyErr_Format(StructError,
                      "pack_into requires a buffer of at least %zd bytes",
                      soself->s_size);
+        PyBuffer_Release(&buf);
         return NULL;
     }
 
     /* Call the guts */
-    if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
+    if (s_pack_internal(soself, args, 2, (char *)buf.buf + offset) != 0) {
+        PyBuffer_Release(&buf);
         return NULL;
     }
+    PyBuffer_Release(&buf);
 
     Py_RETURN_NONE;
 }
index e4885d1..7ce3b78 100644 (file)
@@ -9,6 +9,7 @@
 #include <float.h>
 #include "structmember.h"
 #include "datetime.h"
+#include "marshal.h"
 
 #ifdef WITH_THREAD
 #include "pythread.h"
@@ -376,6 +377,105 @@ test_broken_memoryview(PyObject* self)
     Py_RETURN_NONE;
 }
 
+static PyObject *
+test_to_contiguous(PyObject* self, PyObject *noargs)
+{
+    int data[9] = {0, -1, 1, -1, 2, -1,  3, -1, 4};
+    int result[5];
+    Py_ssize_t itemsize = sizeof(int);
+    Py_ssize_t shape = 5;
+    Py_ssize_t strides = 2 * itemsize;
+    Py_buffer view = {
+        data,
+        NULL,
+        5 * itemsize,
+        itemsize,
+        1,
+        1,
+        NULL,
+        &shape,
+        &strides,
+        NULL,
+        {0, 0},
+        NULL
+    };
+    int i;
+
+    PyBuffer_ToContiguous(result, &view, view.len, 'C');
+    for (i = 0; i < 5; i++) {
+        if (result[i] != i) {
+            PyErr_SetString(TestError,
+                "test_to_contiguous: incorrect result");
+            return NULL;
+        }
+    }
+
+    view.buf = &data[8];
+    view.strides[0] = -2 * itemsize;
+
+    PyBuffer_ToContiguous(result, &view, view.len, 'C');
+    for (i = 0; i < 5; i++) {
+        if (result[i] != 4-i) {
+            PyErr_SetString(TestError,
+                "test_to_contiguous: incorrect result");
+            return NULL;
+        }
+    }
+
+    Py_RETURN_NONE;
+}
+
+static PyObject *
+test_from_contiguous(PyObject* self, PyObject *noargs)
+{
+    int data[9] = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
+    int init[5] = {0, 1, 2, 3, 4};
+    Py_ssize_t itemsize = sizeof(int);
+    Py_ssize_t shape = 5;
+    Py_ssize_t strides = 2 * itemsize;
+    Py_buffer view = {
+        data,
+        NULL,
+        5 * itemsize,
+        itemsize,
+        1,
+        1,
+        NULL,
+        &shape,
+        &strides,
+        NULL,
+        {0, 0},
+        NULL
+    };
+    int *ptr;
+    int i;
+
+    PyBuffer_FromContiguous(&view, init, view.len, 'C');
+    ptr = view.buf;
+    for (i = 0; i < 5; i++) {
+        if (ptr[2*i] != i) {
+            PyErr_SetString(TestError,
+                "test_from_contiguous: incorrect result");
+            return NULL;
+        }
+    }
+
+    view.buf = &data[8];
+    view.strides[0] = -2 * itemsize;
+
+    PyBuffer_FromContiguous(&view, init, view.len, 'C');
+    ptr = view.buf;
+    for (i = 0; i < 5; i++) {
+        if (*(ptr-2*i) != i) {
+            PyErr_SetString(TestError,
+                "test_from_contiguous: incorrect result");
+            return NULL;
+        }
+    }
+
+    Py_RETURN_NONE;
+}
+
 
 /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG)
    PyLong_{As, From}{Unsigned,}LongLong().
@@ -1776,6 +1876,159 @@ exit:
 }
 #endif   /* WITH_THREAD */
 
+/* marshal */
+
+static PyObject*
+pymarshal_write_long_to_file(PyObject* self, PyObject *args)
+{
+    long value;
+    char *filename;
+    int version;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "lsi:pymarshal_write_long_to_file",
+                          &value, &filename, &version))
+        return NULL;
+
+    fp = fopen(filename, "wb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    PyMarshal_WriteLongToFile(value, fp, version);
+
+    fclose(fp);
+    if (PyErr_Occurred())
+        return NULL;
+    Py_RETURN_NONE;
+}
+
+static PyObject*
+pymarshal_write_object_to_file(PyObject* self, PyObject *args)
+{
+    PyObject *obj;
+    char *filename;
+    int version;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "Osi:pymarshal_write_object_to_file",
+                          &obj, &filename, &version))
+        return NULL;
+
+    fp = fopen(filename, "wb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    PyMarshal_WriteObjectToFile(obj, fp, version);
+
+    fclose(fp);
+    if (PyErr_Occurred())
+        return NULL;
+    Py_RETURN_NONE;
+}
+
+static PyObject*
+pymarshal_read_short_from_file(PyObject* self, PyObject *args)
+{
+    int value;
+    long pos;
+    char *filename;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "s:pymarshal_read_short_from_file", &filename))
+        return NULL;
+
+    fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    value = PyMarshal_ReadShortFromFile(fp);
+    pos = ftell(fp);
+
+    fclose(fp);
+    if (PyErr_Occurred())
+        return NULL;
+    return Py_BuildValue("il", value, pos);
+}
+
+static PyObject*
+pymarshal_read_long_from_file(PyObject* self, PyObject *args)
+{
+    long value, pos;
+    char *filename;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "s:pymarshal_read_long_from_file", &filename))
+        return NULL;
+
+    fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    value = PyMarshal_ReadLongFromFile(fp);
+    pos = ftell(fp);
+
+    fclose(fp);
+    if (PyErr_Occurred())
+        return NULL;
+    return Py_BuildValue("ll", value, pos);
+}
+
+static PyObject*
+pymarshal_read_last_object_from_file(PyObject* self, PyObject *args)
+{
+    PyObject *obj;
+    long pos;
+    char *filename;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "s:pymarshal_read_last_object_from_file", &filename))
+        return NULL;
+
+    fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    obj = PyMarshal_ReadLastObjectFromFile(fp);
+    pos = ftell(fp);
+
+    fclose(fp);
+    return Py_BuildValue("Nl", obj, pos);
+}
+
+static PyObject*
+pymarshal_read_object_from_file(PyObject* self, PyObject *args)
+{
+    PyObject *obj;
+    long pos;
+    char *filename;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "s:pymarshal_read_object_from_file", &filename))
+        return NULL;
+
+    fp = fopen(filename, "rb");
+    if (fp == NULL) {
+        PyErr_SetFromErrno(PyExc_OSError);
+        return NULL;
+    }
+
+    obj = PyMarshal_ReadObjectFromFile(fp);
+    pos = ftell(fp);
+
+    fclose(fp);
+    return Py_BuildValue("Nl", obj, pos);
+}
+
 
 static PyMethodDef TestMethods[] = {
     {"raise_exception",         raise_exception,                 METH_VARARGS},
@@ -1785,6 +2038,8 @@ static PyMethodDef TestMethods[] = {
     {"test_dict_iteration",     (PyCFunction)test_dict_iteration,METH_NOARGS},
     {"test_lazy_hash_inheritance",      (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
     {"test_broken_memoryview",          (PyCFunction)test_broken_memoryview,METH_NOARGS},
+    {"test_to_contiguous",      (PyCFunction)test_to_contiguous, METH_NOARGS},
+    {"test_from_contiguous",    (PyCFunction)test_from_contiguous, METH_NOARGS},
     {"test_long_api",           (PyCFunction)test_long_api,      METH_NOARGS},
     {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
      METH_NOARGS},
@@ -1839,6 +2094,18 @@ static PyMethodDef TestMethods[] = {
     {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O,
      PyDoc_STR("set_error_class(error_class) -> None")},
 #endif
+    {"pymarshal_write_long_to_file",
+        pymarshal_write_long_to_file, METH_VARARGS},
+    {"pymarshal_write_object_to_file",
+        pymarshal_write_object_to_file, METH_VARARGS},
+    {"pymarshal_read_short_from_file",
+        pymarshal_read_short_from_file, METH_VARARGS},
+    {"pymarshal_read_long_from_file",
+        pymarshal_read_long_from_file, METH_VARARGS},
+    {"pymarshal_read_last_object_from_file",
+        pymarshal_read_last_object_from_file, METH_VARARGS},
+    {"pymarshal_read_object_from_file",
+        pymarshal_read_object_from_file, METH_VARARGS},
     {NULL, NULL} /* sentinel */
 };
 
index acc0110..58456a4 100644 (file)
@@ -80,7 +80,7 @@ Copyright (C) 1994 Steen Lumholt.
 #define CONST
 #endif
 
-#if TK_VERSION_HEX < 0x08030102
+#if TK_HEX_VERSION < 0x08030201
 #error "Tk older than 8.3.1 not supported"
 #endif
 
@@ -96,6 +96,12 @@ Copyright (C) 1994 Steen Lumholt.
 #error "unsupported Tcl configuration"
 #endif
 
+#if TK_HEX_VERSION >= 0x08050208 && TK_HEX_VERSION < 0x08060000 || \
+    TK_HEX_VERSION >= 0x08060200
+#define HAVE_LIBTOMMAMTH
+#include <tclTomMath.h>
+#endif
+
 #if !(defined(MS_WINDOWS) || defined(__CYGWIN__))
 #define HAVE_CREATEFILEHANDLER
 #endif
@@ -257,13 +263,16 @@ typedef struct {
     int dispatching;
     /* We cannot include tclInt.h, as this is internal.
        So we cache interesting types here. */
-    Tcl_ObjType *BooleanType;
-    Tcl_ObjType *ByteArrayType;
-    Tcl_ObjType *DoubleType;
-    Tcl_ObjType *IntType;
-    Tcl_ObjType *ListType;
-    Tcl_ObjType *ProcBodyType;
-    Tcl_ObjType *StringType;
+    const Tcl_ObjType *OldBooleanType;
+    const Tcl_ObjType *BooleanType;
+    const Tcl_ObjType *ByteArrayType;
+    const Tcl_ObjType *DoubleType;
+    const Tcl_ObjType *IntType;
+    const Tcl_ObjType *WideIntType;
+    const Tcl_ObjType *BignumType;
+    const Tcl_ObjType *ListType;
+    const Tcl_ObjType *ProcBodyType;
+    const Tcl_ObjType *StringType;
 } TkappObject;
 
 #define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type)
@@ -733,10 +742,13 @@ Tkapp_New(char *screenName, char *baseName, char *className,
     }
 #endif
 
-    v->BooleanType = Tcl_GetObjType("boolean");
+    v->OldBooleanType = Tcl_GetObjType("boolean");
+    v->BooleanType = Tcl_GetObjType("booleanString");
     v->ByteArrayType = Tcl_GetObjType("bytearray");
     v->DoubleType = Tcl_GetObjType("double");
     v->IntType = Tcl_GetObjType("int");
+    v->WideIntType = Tcl_GetObjType("wideInt");
+    v->BignumType = Tcl_GetObjType("bignum");
     v->ListType = Tcl_GetObjType("list");
     v->ProcBodyType = Tcl_GetObjType("procbody");
     v->StringType = Tcl_GetObjType("string");
@@ -1033,6 +1045,45 @@ statichere PyTypeObject PyTclObject_Type = {
 #define CHECK_STRING_LENGTH(s)
 #endif
 
+#ifdef HAVE_LIBTOMMAMTH
+static Tcl_Obj*
+asBignumObj(PyObject *value)
+{
+    Tcl_Obj *result;
+    int neg;
+    PyObject *hexstr;
+    char *hexchars;
+    mp_int bigValue;
+
+    neg = Py_SIZE(value) < 0;
+    hexstr = _PyLong_Format(value, 16, 0, 1);
+    if (hexstr == NULL)
+        return NULL;
+    hexchars = PyString_AsString(hexstr);
+    if (hexchars == NULL) {
+        Py_DECREF(hexstr);
+        return NULL;
+    }
+    hexchars += neg + 2; /* skip sign and "0x" */
+    mp_init(&bigValue);
+    if (mp_read_radix(&bigValue, hexchars, 16) != MP_OKAY) {
+        mp_clear(&bigValue);
+        Py_DECREF(hexstr);
+        PyErr_NoMemory();
+        return NULL;
+    }
+    Py_DECREF(hexstr);
+    bigValue.sign = neg ? MP_NEG : MP_ZPOS;
+    result = Tcl_NewBignumObj(&bigValue);
+    mp_clear(&bigValue);
+    if (result == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+    return result;
+}
+#endif
+
 static Tcl_Obj*
 AsObj(PyObject *value)
 {
@@ -1041,13 +1092,52 @@ AsObj(PyObject *value)
     if (PyString_Check(value))
         return Tcl_NewStringObj(PyString_AS_STRING(value),
                                 PyString_GET_SIZE(value));
-    else if (PyBool_Check(value))
+
+    if (PyBool_Check(value))
         return Tcl_NewBooleanObj(PyObject_IsTrue(value));
-    else if (PyInt_Check(value))
+
+    if (PyInt_Check(value))
         return Tcl_NewLongObj(PyInt_AS_LONG(value));
-    else if (PyFloat_Check(value))
+
+    if (PyLong_CheckExact(value)) {
+        int overflow;
+        long longValue;
+#ifdef TCL_WIDE_INT_TYPE
+        Tcl_WideInt wideValue;
+#endif
+        longValue = PyLong_AsLongAndOverflow(value, &overflow);
+        if (!overflow) {
+            return Tcl_NewLongObj(longValue);
+        }
+        /* If there is an overflow in the long conversion,
+           fall through to wideInt handling. */
+#ifdef TCL_WIDE_INT_TYPE
+        if (_PyLong_AsByteArray((PyLongObject *)value,
+                                (unsigned char *)(void *)&wideValue,
+                                sizeof(wideValue),
+#ifdef WORDS_BIGENDIAN
+                                0,
+#else
+                                1,
+#endif
+                                /* signed */ 1) == 0) {
+            return Tcl_NewWideIntObj(wideValue);
+        }
+        PyErr_Clear();
+#endif
+        /* If there is an overflow in the wideInt conversion,
+           fall through to bignum handling. */
+#ifdef HAVE_LIBTOMMAMTH
+        return asBignumObj(value);
+#endif
+        /* If there is no wideInt or bignum support,
+           fall through to default object handling. */
+    }
+
+    if (PyFloat_Check(value))
         return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
-    else if (PyTuple_Check(value)) {
+
+    if (PyTuple_Check(value)) {
         Tcl_Obj **argv;
         Py_ssize_t size, i;
 
@@ -1067,8 +1157,9 @@ AsObj(PyObject *value)
         ckfree(FREECAST argv);
         return result;
     }
+
 #ifdef Py_USING_UNICODE
-    else if (PyUnicode_Check(value)) {
+    if (PyUnicode_Check(value)) {
         Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
         Py_ssize_t size = PyUnicode_GET_SIZE(value);
         /* This #ifdef assumes that Tcl uses UCS-2.
@@ -1111,15 +1202,16 @@ AsObj(PyObject *value)
 #else
         return Tcl_NewUnicodeObj(inbuf, size);
 #endif
-
     }
 #endif
-    else if(PyTclObject_Check(value)) {
+
+    if(PyTclObject_Check(value)) {
         Tcl_Obj *v = ((PyTclObject*)value)->value;
         Tcl_IncrRefCount(v);
         return v;
     }
-    else {
+
+    {
         PyObject *v = PyObject_Str(value);
         if (!v)
             return 0;
@@ -1129,21 +1221,90 @@ AsObj(PyObject *value)
     }
 }
 
+static PyObject *
+fromBoolean(PyObject* tkapp, Tcl_Obj *value)
+{
+    int boolValue;
+    if (Tcl_GetBooleanFromObj(Tkapp_Interp(tkapp), value, &boolValue) == TCL_ERROR)
+        return Tkinter_Error(tkapp);
+    return PyBool_FromLong(boolValue);
+}
+
+#ifdef TCL_WIDE_INT_TYPE
+static PyObject*
+fromWideIntObj(PyObject* tkapp, Tcl_Obj *value)
+{
+        Tcl_WideInt wideValue;
+        if (Tcl_GetWideIntFromObj(Tkapp_Interp(tkapp), value, &wideValue) == TCL_OK) {
+#ifdef HAVE_LONG_LONG
+            if (sizeof(wideValue) <= SIZEOF_LONG_LONG)
+                return PyLong_FromLongLong(wideValue);
+#endif
+            return _PyLong_FromByteArray((unsigned char *)(void *)&wideValue,
+                                         sizeof(wideValue),
+#ifdef WORDS_BIGENDIAN
+                                         0,
+#else
+                                         1,
+#endif
+                                         /* signed */ 1);
+        }
+        return NULL;
+}
+#endif
+
+#ifdef HAVE_LIBTOMMAMTH
+static PyObject*
+fromBignumObj(PyObject* tkapp, Tcl_Obj *value)
+{
+    mp_int bigValue;
+    unsigned long numBytes;
+    unsigned char *bytes;
+    PyObject *res;
+
+    if (Tcl_GetBignumFromObj(Tkapp_Interp(tkapp), value, &bigValue) != TCL_OK)
+        return Tkinter_Error(tkapp);
+    numBytes = mp_unsigned_bin_size(&bigValue);
+    bytes = PyMem_Malloc(numBytes);
+    if (bytes == NULL) {
+        mp_clear(&bigValue);
+        return PyErr_NoMemory();
+    }
+    if (mp_to_unsigned_bin_n(&bigValue, bytes,
+                                &numBytes) != MP_OKAY) {
+        mp_clear(&bigValue);
+        PyMem_Free(bytes);
+        return PyErr_NoMemory();
+    }
+    res = _PyLong_FromByteArray(bytes, numBytes,
+                                /* big-endian */ 0,
+                                /* unsigned */ 0);
+    PyMem_Free(bytes);
+    if (res != NULL && bigValue.sign == MP_NEG) {
+        PyObject *res2 = PyNumber_Negative(res);
+        Py_DECREF(res);
+        res = res2;
+    }
+    mp_clear(&bigValue);
+    return res;
+}
+#endif
+
 static PyObject*
 FromObj(PyObject* tkapp, Tcl_Obj *value)
 {
     PyObject *result = NULL;
     TkappObject *app = (TkappObject*)tkapp;
+    Tcl_Interp *interp = Tkapp_Interp(tkapp);
 
     if (value->typePtr == NULL) {
         result = fromTclStringAndSize(value->bytes, value->length);
         return result;
     }
 
-    if (value->typePtr == app->BooleanType) {
-        result = value->internalRep.longValue ? Py_True : Py_False;
-        Py_INCREF(result);
-        return result;
+    if (value->typePtr == app->BooleanType ||
+        value->typePtr == app->OldBooleanType) {
+        return fromBoolean(tkapp, value);
     }
 
     if (value->typePtr == app->ByteArrayType) {
@@ -1157,8 +1318,32 @@ FromObj(PyObject* tkapp, Tcl_Obj *value)
     }
 
     if (value->typePtr == app->IntType) {
-        return PyInt_FromLong(value->internalRep.longValue);
+        long longValue;
+        if (Tcl_GetLongFromObj(interp, value, &longValue) == TCL_OK)
+            return PyInt_FromLong(longValue);
+        /* If there is an error in the long conversion,
+           fall through to wideInt handling. */
+    }
+
+#ifdef TCL_WIDE_INT_TYPE
+    if (value->typePtr == app->IntType ||
+        value->typePtr == app->WideIntType) {
+        result = fromWideIntObj(tkapp, value);
+        if (result != NULL || PyErr_Occurred())
+            return result;
+        Tcl_ResetResult(interp);
+        /* If there is an error in the wideInt conversion,
+           fall through to bignum handling. */
+    }
+#endif
+
+#ifdef HAVE_LIBTOMMAMTH
+    if (value->typePtr == app->IntType ||
+        value->typePtr == app->WideIntType ||
+        value->typePtr == app->BignumType) {
+        return fromBignumObj(tkapp, value);
     }
+#endif
 
     if (value->typePtr == app->ListType) {
         int size;
@@ -1166,15 +1351,14 @@ FromObj(PyObject* tkapp, Tcl_Obj *value)
         PyObject *elem;
         Tcl_Obj *tcl_elem;
 
-        status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
+        status = Tcl_ListObjLength(interp, value, &size);
         if (status == TCL_ERROR)
             return Tkinter_Error(tkapp);
         result = PyTuple_New(size);
         if (!result)
             return NULL;
         for (i = 0; i < size; i++) {
-            status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
-                                      value, i, &tcl_elem);
+            status = Tcl_ListObjIndex(interp, value, i, &tcl_elem);
             if (status == TCL_ERROR) {
                 Py_DECREF(result);
                 return Tkinter_Error(tkapp);
@@ -1222,6 +1406,24 @@ FromObj(PyObject* tkapp, Tcl_Obj *value)
 #endif
     }
 
+#if TK_HEX_VERSION >= 0x08050000
+    if (app->BooleanType == NULL &&
+        strcmp(value->typePtr->name, "booleanString") == 0) {
+        /* booleanString type is not registered in Tcl */
+        app->BooleanType = value->typePtr;
+        return fromBoolean(tkapp, value);
+    }
+#endif
+
+#ifdef HAVE_LIBTOMMAMTH
+    if (app->BignumType == NULL &&
+        strcmp(value->typePtr->name, "bignum") == 0) {
+        /* bignum type is not registered in Tcl */
+        app->BignumType = value->typePtr;
+        return fromBignumObj(tkapp, value);
+    }
+#endif
+
     return newPyTclObject(value);
 }
 
@@ -1896,11 +2098,16 @@ static PyObject *
 Tkapp_GetInt(PyObject *self, PyObject *args)
 {
     char *s;
-    int v;
+#if defined(TCL_WIDE_INT_TYPE) || defined(HAVE_LIBTOMMAMTH)
+    Tcl_Obj *value;
+    PyObject *result;
+#else
+    int intValue;
+#endif
 
     if (PyTuple_Size(args) == 1) {
         PyObject* o = PyTuple_GetItem(args, 0);
-        if (PyInt_Check(o)) {
+        if (PyInt_Check(o) || PyLong_Check(o)) {
             Py_INCREF(o);
             return o;
         }
@@ -1908,9 +2115,31 @@ Tkapp_GetInt(PyObject *self, PyObject *args)
     if (!PyArg_ParseTuple(args, "s:getint", &s))
         return NULL;
     CHECK_STRING_LENGTH(s);
-    if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+#if defined(TCL_WIDE_INT_TYPE) || defined(HAVE_LIBTOMMAMTH)
+    value = Tcl_NewStringObj(s, -1);
+    if (value == NULL)
         return Tkinter_Error(self);
-    return Py_BuildValue("i", v);
+    /* Don't use Tcl_GetInt() because it returns ambiguous result for value
+       in ranges -2**32..-2**31-1 and 2**31..2**32-1 (on 32-bit platform).
+
+       Prefer bignum because Tcl_GetWideIntFromObj returns ambiguous result for
+       value in ranges -2**64..-2**63-1 and 2**63..2**64-1 (on 32-bit platform).
+     */
+#ifdef HAVE_LIBTOMMAMTH
+    result = fromBignumObj(self, value);
+#else
+    result = fromWideIntObj(self, value);
+#endif
+    Tcl_DecrRefCount(value);
+    if (result != NULL)
+        return PyNumber_Int(result);
+    if (PyErr_Occurred())
+        return NULL;
+#else
+    if (Tcl_GetInt(Tkapp_Interp(self), s, &intValue) == TCL_OK)
+        return PyInt_FromLong(intValue);
+#endif
+    return Tkinter_Error(self);
 }
 
 static PyObject *
@@ -1935,19 +2164,26 @@ Tkapp_GetDouble(PyObject *self, PyObject *args)
 }
 
 static PyObject *
-Tkapp_GetBoolean(PyObject *self, PyObject *args)
+Tkapp_GetBoolean(PyObject *self, PyObject *arg)
 {
     char *s;
     int v;
 
-    if (PyTuple_Size(args) == 1) {
-        PyObject *o = PyTuple_GetItem(args, 0);
-        if (PyInt_Check(o)) {
-            Py_INCREF(o);
-            return o;
-        }
+    if (PyInt_Check(arg)) /* int or bool */
+        return PyBool_FromLong(PyInt_AS_LONG(arg));
+
+    if (PyLong_Check(arg))
+        return PyBool_FromLong(Py_SIZE(arg) != 0);
+
+    if (PyTclObject_Check(arg)) {
+        if (Tcl_GetBooleanFromObj(Tkapp_Interp(self),
+                                  ((PyTclObject*)arg)->value,
+                                  &v) == TCL_ERROR)
+            return Tkinter_Error(self);
+        return PyBool_FromLong(v);
     }
-    if (!PyArg_ParseTuple(args, "s:getboolean", &s))
+
+    if (!PyArg_Parse(arg, "s:getboolean", &s))
         return NULL;
     CHECK_STRING_LENGTH(s);
     if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
@@ -3008,7 +3244,7 @@ static PyMethodDef Tkapp_methods[] =
     {"globalunsetvar",     Tkapp_GlobalUnsetVar, METH_VARARGS},
     {"getint",                 Tkapp_GetInt, METH_VARARGS},
     {"getdouble",              Tkapp_GetDouble, METH_VARARGS},
-    {"getboolean",             Tkapp_GetBoolean, METH_VARARGS},
+    {"getboolean",             Tkapp_GetBoolean, METH_O},
     {"exprstring",             Tkapp_ExprString, METH_VARARGS},
     {"exprlong",               Tkapp_ExprLong, METH_VARARGS},
     {"exprdouble",             Tkapp_ExprDouble, METH_VARARGS},
index ab4e659..6e0d2ce 100644 (file)
@@ -15,7 +15,7 @@
 #undef hz
 #endif
 
-/* GBK and GB2312 map differently in few codepoints that are listed below:
+/* GBK and GB2312 map differently in few code points that are listed below:
  *
  *              gb2312                          gbk
  * A1A4         U+30FB KATAKANA MIDDLE DOT      U+00B7 MIDDLE DOT
index 558a42f..6ee7bb1 100644 (file)
@@ -164,7 +164,7 @@ DECODER(big5hkscs)
         default: return 2;
         }
 
-        NEXT(2, 2) /* all decoded codepoints are pairs, above. */
+        NEXT(2, 2) /* all decoded code points are pairs, above. */
     }
 
     return 0;
index 9272e36..1fc83fe 100644 (file)
@@ -64,7 +64,7 @@ ENCODER(euc_kr)
             OUT1(EUCKR_JAMO_FIRSTBYTE)
             OUT2(EUCKR_JAMO_FILLER)
 
-            /* All codepoints in CP949 extension are in unicode
+            /* All code points in CP949 extension are in unicode
              * Hangul Syllable area. */
             assert(0xac00 <= c && c <= 0xd7a3);
             c -= 0xac00;
index 7e8390a..399e9dc 100644 (file)
 #include "multibytecodec.h"
 
 
-/* a unicode "undefined" codepoint */
+/* a unicode "undefined" code point */
 #define UNIINV  0xFFFE
 
-/* internal-use DBCS codepoints which aren't used by any charsets */
+/* internal-use DBCS code points which aren't used by any charsets */
 #define NOCHAR  0xFFFF
 #define MULTIC  0xFFFE
 #define DBCINV  0xFFFD
index 14fed3e..3f75fe7 100644 (file)
@@ -170,8 +170,10 @@ expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize)
     orgsize = PyString_GET_SIZE(buf->outobj);
     incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
 
-    if (orgsize > PY_SSIZE_T_MAX - incsize)
+    if (orgsize > PY_SSIZE_T_MAX - incsize) {
+        PyErr_NoMemory();
         return -1;
+    }
 
     if (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
         return -1;
@@ -182,11 +184,11 @@ expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize)
 
     return 0;
 }
-#define REQUIRE_ENCODEBUFFER(buf, s) {                                  \
-    if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end)             \
+#define REQUIRE_ENCODEBUFFER(buf, s) do {                               \
+    if ((s) < 0 || (s) > (buf)->outbuf_end - (buf)->outbuf)             \
         if (expand_encodebuffer(buf, s) == -1)                          \
             goto errorexit;                                             \
-}
+} while(0)
 
 static int
 expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
@@ -205,11 +207,11 @@ expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
 
     return 0;
 }
-#define REQUIRE_DECODEBUFFER(buf, s) {                                  \
-    if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end)             \
+#define REQUIRE_DECODEBUFFER(buf, s) do {                               \
+    if ((s) < 0 || (s) > (buf)->outbuf_end - (buf)->outbuf)             \
         if (expand_decodebuffer(buf, s) == -1)                          \
             goto errorexit;                                             \
-}
+} while(0)
 
 
 /**
@@ -327,10 +329,11 @@ multibytecodec_encerror(MultibyteCodec *codec,
     }
 
     retstrsize = PyString_GET_SIZE(retstr);
-    REQUIRE_ENCODEBUFFER(buf, retstrsize);
-
-    memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
-    buf->outbuf += retstrsize;
+    if (retstrsize > 0) {
+        REQUIRE_ENCODEBUFFER(buf, retstrsize);
+        memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
+        buf->outbuf += retstrsize;
+    }
 
     newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
     if (newpos < 0 && !PyErr_Occurred())
index 5720678..26e7aba 100644 (file)
@@ -192,7 +192,7 @@ c_acosh(Py_complex z)
 PyDoc_STRVAR(c_acosh_doc,
 "acosh(x)\n"
 "\n"
-"Return the hyperbolic arccosine of x.");
+"Return the inverse hyperbolic cosine of x.");
 
 
 static Py_complex
@@ -249,7 +249,7 @@ c_asinh(Py_complex z)
 PyDoc_STRVAR(c_asinh_doc,
 "asinh(x)\n"
 "\n"
-"Return the hyperbolic arc sine of x.");
+"Return the inverse hyperbolic sine of x.");
 
 
 static Py_complex
@@ -353,7 +353,7 @@ c_atanh(Py_complex z)
 PyDoc_STRVAR(c_atanh_doc,
 "atanh(x)\n"
 "\n"
-"Return the hyperbolic arc tangent of x.");
+"Return the inverse hyperbolic tangent of x.");
 
 
 static Py_complex
index cd45eb9..e5b2b74 100644 (file)
@@ -1842,11 +1842,19 @@ product_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         }
     }
 
-    assert(PyTuple_Check(args));
-    nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args);
+    assert(PyTuple_CheckExact(args));
+    if (repeat == 0) {
+        nargs = 0;
+    } else {
+        nargs = PyTuple_GET_SIZE(args);
+        if ((size_t)nargs > PY_SSIZE_T_MAX/sizeof(Py_ssize_t)/repeat) {
+            PyErr_SetString(PyExc_OverflowError, "repeat argument too large");
+            return NULL;
+        }
+    }
     npools = nargs * repeat;
 
-    indices = PyMem_Malloc(npools * sizeof(Py_ssize_t));
+    indices = PyMem_New(Py_ssize_t, npools);
     if (indices == NULL) {
         PyErr_NoMemory();
         goto error;
@@ -2093,7 +2101,7 @@ combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         goto error;
     }
 
-    indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+    indices = PyMem_New(Py_ssize_t, r);
     if (indices == NULL) {
         PyErr_NoMemory();
         goto error;
@@ -2342,7 +2350,7 @@ cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         goto error;
     }
 
-    indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+    indices = PyMem_New(Py_ssize_t, r);
     if (indices == NULL) {
         PyErr_NoMemory();
         goto error;
@@ -2595,8 +2603,8 @@ permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         goto error;
     }
 
-    indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
-    cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
+    indices = PyMem_New(Py_ssize_t, n);
+    cycles = PyMem_New(Py_ssize_t, r);
     if (indices == NULL || cycles == NULL) {
         PyErr_NoMemory();
         goto error;
index 845fb9b..670e52d 100644 (file)
@@ -809,18 +809,18 @@ math_2(PyObject *args, double (*func) (double, double), char *funcname)
 FUNC1(acos, acos, 0,
       "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
 FUNC1(acosh, m_acosh, 0,
-      "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
+      "acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
 FUNC1(asin, asin, 0,
       "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
 FUNC1(asinh, m_asinh, 0,
-      "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
+      "asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
 FUNC1(atan, atan, 0,
       "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
 FUNC2(atan2, m_atan2,
       "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
       "Unlike atan(y/x), the signs of both x and y are considered.")
 FUNC1(atanh, m_atanh, 0,
-      "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
+      "atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
 FUNC1(ceil, ceil, 0,
       "ceil(x)\n\nReturn the ceiling of x as a float.\n"
       "This is the smallest integral value >= x.")
index 4d0c8fa..4e86d32 100644 (file)
@@ -474,6 +474,61 @@ OverflowUp:
 #endif /* MS_WINDOWS */
 
 
+#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
+static int
+_Py_Dev_Converter(PyObject *obj, void *p)
+{
+    PyObject *index = PyNumber_Index(obj);
+    if (index == NULL)
+        return 0;
+    if (PyInt_Check(index)) {
+        long x = PyInt_AS_LONG(index);
+        Py_DECREF(index);
+        if (x == -1 && PyErr_Occurred())
+            return 0;
+        if (x < 0) {
+            PyErr_SetString(PyExc_OverflowError,
+                            "can't convert negative number to unsigned long");
+            return 0;
+        }
+        *((dev_t *)p) = (unsigned long)x;
+    }
+    else if (PyLong_Check(index)) {
+#ifdef HAVE_LONG_LONG
+        *((dev_t *)p) = PyLong_AsUnsignedLongLong(index);
+#else
+        *((dev_t *)p) = PyLong_AsUnsignedLong(index);
+#endif
+        Py_DECREF(index);
+        if (PyErr_Occurred())
+            return 0;
+    }
+    else {
+        Py_DECREF(index);
+        PyErr_Format(PyExc_TypeError,
+                     "expected int/long, %s found",
+                     Py_TYPE(obj)->tp_name);
+        return 0;
+    }
+    return 1;
+}
+
+#ifdef HAVE_LONG_LONG
+static PyObject *
+_PyInt_FromDev(PY_LONG_LONG v)
+{
+    if (LONG_MIN <= v && v <= LONG_MAX)
+        return PyInt_FromLong((long)v);
+    else
+        return PyLong_FromLongLong(v);
+}
+#else
+#  define _PyInt_FromDev PyInt_FromLong
+#endif
+
+#endif
+
+
 #if defined _MSC_VER && _MSC_VER >= 1400
 /* Microsoft CRT in VS2005 and higher will verify that a filehandle is
  * valid and raise an assertion if it isn't.
@@ -1426,11 +1481,10 @@ _pystat_fromstructstat(STRUCT_STAT *st)
 #else
     PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long)st->st_ino));
 #endif
-#if defined(HAVE_LONG_LONG) && !defined(MS_WINDOWS)
-    PyStructSequence_SET_ITEM(v, 2,
-                              PyLong_FromLongLong((PY_LONG_LONG)st->st_dev));
+#ifdef MS_WINDOWS
+    PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
 #else
-    PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long)st->st_dev));
+    PyStructSequence_SET_ITEM(v, 2, _PyInt_FromDev(st->st_dev));
 #endif
     PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long)st->st_nlink));
 #if defined(MS_WINDOWS)
@@ -7009,9 +7063,11 @@ posix_mknod(PyObject *self, PyObject *args)
 {
     char *filename;
     int mode = 0600;
-    int device = 0;
+    dev_t device = 0;
     int res;
-    if (!PyArg_ParseTuple(args, "s|ii:mknod", &filename, &mode, &device))
+    if (!PyArg_ParseTuple(args, "s|iO&:mknod",
+        &filename, &mode,
+        _Py_Dev_Converter, &device))
         return NULL;
     Py_BEGIN_ALLOW_THREADS
     res = mknod(filename, mode, device);
@@ -7031,8 +7087,8 @@ Extracts a device major number from a raw device number.");
 static PyObject *
 posix_major(PyObject *self, PyObject *args)
 {
-    int device;
-    if (!PyArg_ParseTuple(args, "i:major", &device))
+    dev_t device;
+    if (!PyArg_ParseTuple(args, "O&:major", _Py_Dev_Converter, &device))
         return NULL;
     return PyInt_FromLong((long)major(device));
 }
@@ -7044,8 +7100,8 @@ Extracts a device minor number from a raw device number.");
 static PyObject *
 posix_minor(PyObject *self, PyObject *args)
 {
-    int device;
-    if (!PyArg_ParseTuple(args, "i:minor", &device))
+    dev_t device;
+    if (!PyArg_ParseTuple(args, "O&:minor", _Py_Dev_Converter, &device))
         return NULL;
     return PyInt_FromLong((long)minor(device));
 }
@@ -7060,7 +7116,7 @@ posix_makedev(PyObject *self, PyObject *args)
     int major, minor;
     if (!PyArg_ParseTuple(args, "ii:makedev", &major, &minor))
         return NULL;
-    return PyInt_FromLong((long)makedev(major, minor));
+    return _PyInt_FromDev(makedev(major, minor));
 }
 #endif /* device macros */
 
@@ -8496,7 +8552,7 @@ posix_sysconf(PyObject *self, PyObject *args)
 
 
 /* This code is used to ensure that the tables of configuration value names
- * are in sorted order as required by conv_confname(), and also to build the
+ * are in sorted order as required by conv_confname(), and also to build
  * the exported dictionaries that are used to publish information about the
  * names available on the host platform.
  *
@@ -8522,7 +8578,6 @@ setup_confname_table(struct constdef *table, size_t tablesize,
 {
     PyObject *d = NULL;
     size_t i;
-
     qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
     d = PyDict_New();
     if (d == NULL)
index 06ae7c6..244d260 100644 (file)
@@ -975,8 +975,6 @@ rlhandler(char *text)
     rl_callback_handler_remove();
 }
 
-extern PyThreadState* _PyOS_ReadlineTState;
-
 static char *
 readline_until_enter_or_signal(char *prompt, int *signal)
 {
index e9e4479..5def531 100644 (file)
@@ -2901,7 +2901,8 @@ sock_sendto(PySocketSockObject *s, PyObject *args)
     char *buf;
     Py_ssize_t len;
     sock_addr_t addrbuf;
-    int addrlen, n = -1, flags, timeout;
+    int addrlen, flags, timeout;
+    long n = -1;
     int arglen;
 
     flags = 0;
@@ -4207,7 +4208,8 @@ socket_getaddrinfo(PyObject *self, PyObject *args)
         goto err;
     }
 
-    if ((all = PyList_New(0)) == NULL)
+    all = PyList_New(0);
+    if (all == NULL)
         goto err;
     for (res = res0; res; res = res->ai_next) {
         PyObject *addr =
index f7e50cd..3c55676 100644 (file)
@@ -4,24 +4,32 @@
 /* This header is used to share some macros between _tkinter.c and
  * tkappinit.c.
  * Be sure to include tk.h before including this header so
- * TK_VERSION_HEX is properly defined. */
+ * TK_HEX_VERSION is properly defined. */
 
 /* TK_RELEASE_LEVEL is always one of the following:
- *     TCL_ALPHA_RELEASE   0
+ *  TCL_ALPHA_RELEASE   0
  *  TCL_BETA_RELEASE    1
  *  TCL_FINAL_RELEASE   2
  */
+#define TK_HEX_VERSION ((TK_MAJOR_VERSION << 24) | \
+                        (TK_MINOR_VERSION << 16) | \
+                        (TK_RELEASE_LEVEL << 8) | \
+                        (TK_RELEASE_SERIAL << 0))
+
+/* TK_VERSION_HEX packs fields in wrong order, not suitable for comparing of
+ * non-final releases.  Left for backward compatibility.
+ */
 #define TK_VERSION_HEX ((TK_MAJOR_VERSION << 24) | \
-               (TK_MINOR_VERSION << 16) | \
-               (TK_RELEASE_SERIAL << 8) | \
-               (TK_RELEASE_LEVEL << 0))
+                        (TK_MINOR_VERSION << 16) | \
+                        (TK_RELEASE_SERIAL << 8) | \
+                        (TK_RELEASE_LEVEL << 0))
 
 /* Protect Tk 8.4.13 and older from a deadlock that happens when trying
  * to load tk after a failed attempt. */
-#if TK_VERSION_HEX < 0x08040e02
+#if TK_HEX_VERSION < 0x0804020e
 #define TKINTER_PROTECT_LOADTK
 #define TKINTER_LOADTK_ERRMSG \
-       "Calling Tk_Init again after a previous call failed might deadlock"
+        "Calling Tk_Init again after a previous call failed might deadlock"
 #endif
 
 #endif /* !TKINTER_H */
index 6f9c7e8..6b01fc7 100644 (file)
@@ -506,8 +506,15 @@ nfd_nfkd(PyObject *self, PyObject *input, int k)
 
     stackptr = 0;
     isize = PyUnicode_GET_SIZE(input);
+    space = isize;
     /* Overallocate at most 10 characters. */
-    space = (isize > 10 ? 10 : isize) + isize;
+    if (space > 10) {
+        if (space <= PY_SSIZE_T_MAX - 10)
+            space += 10;
+    }
+    else {
+        space *= 2;
+    }
     result = PyUnicode_FromUnicode(NULL, space);
     if (!result)
         return NULL;
index 5707eb2..64a1a38 100644 (file)
@@ -499,7 +499,7 @@ PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
 
     /* Otherwise a more elaborate scheme is needed */
 
-    /* XXX(nnorwitz): need to check for overflow! */
+    /* view->ndim <= 64 */
     indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
     if (indices == NULL) {
         PyErr_NoMemory();
@@ -521,10 +521,10 @@ PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
      */
     elements = len / view->itemsize;
     while (elements--) {
-        addone(view->ndim, indices, view->shape);
         ptr = PyBuffer_GetPointer(view, indices);
         memcpy(dest, ptr, view->itemsize);
         dest += view->itemsize;
+        addone(view->ndim, indices, view->shape);
     }
     PyMem_Free(indices);
     return 0;
@@ -550,7 +550,7 @@ PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
 
     /* Otherwise a more elaborate scheme is needed */
 
-    /* XXX(nnorwitz): need to check for overflow! */
+    /* view->ndim <= 64 */
     indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
     if (indices == NULL) {
         PyErr_NoMemory();
@@ -572,10 +572,10 @@ PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
      */
     elements = len / view->itemsize;
     while (elements--) {
-        addone(view->ndim, indices, view->shape);
         ptr = PyBuffer_GetPointer(view, indices);
         memcpy(ptr, src, view->itemsize);
         src += view->itemsize;
+        addone(view->ndim, indices, view->shape);
     }
 
     PyMem_Free(indices);
index 2bec0fb..0ce7f6c 100644 (file)
@@ -271,6 +271,7 @@ PyFloat_AsDouble(PyObject *op)
     if (fo == NULL)
         return -1;
     if (!PyFloat_Check(fo)) {
+        Py_DECREF(fo);
         PyErr_SetString(PyExc_TypeError,
                         "nb_float should return float object");
         return -1;
index f753643..1f43ba2 100644 (file)
@@ -1800,7 +1800,8 @@ merge_collapse(MergeState *ms)
     assert(ms);
     while (ms->n > 1) {
         Py_ssize_t n = ms->n - 2;
-        if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
+        if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
+            (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
             if (p[n-1].len < p[n+1].len)
                 --n;
             if (merge_at(ms, n) < 0)
index 1434206..85eee61 100644 (file)
@@ -1,5 +1,23 @@
 #include "Python.h"
 
+#if defined(__has_feature)  /* Clang */
+ #if __has_feature(address_sanitizer)  /* is ASAN enabled? */
+  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
+        __attribute__((no_address_safety_analysis)) \
+        __attribute__ ((noinline))
+ #else
+  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
+ #endif
+#else
+ #if defined(__SANITIZE_ADDRESS__)  /* GCC 4.8.x, is ASAN enabled? */
+  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
+        __attribute__((no_address_safety_analysis)) \
+        __attribute__ ((noinline))
+ #else
+  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
+ #endif
+#endif
+
 #ifdef WITH_PYMALLOC
 
 #ifdef HAVE_MMAP
@@ -971,6 +989,7 @@ redirect:
 /* free */
 
 #undef PyObject_Free
+ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
 void
 PyObject_Free(void *p)
 {
@@ -1201,6 +1220,7 @@ redirect:
  */
 
 #undef PyObject_Realloc
+ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
 void *
 PyObject_Realloc(void *p, size_t nbytes)
 {
index a3c185e..5d72806 100644 (file)
@@ -761,27 +761,15 @@ tuple_getnewargs(PyTupleObject *v)
 
 }
 
-static PyObject *
-tuple_sizeof(PyTupleObject *self)
-{
-    Py_ssize_t res;
-
-    res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *);
-    return PyInt_FromSsize_t(res);
-}
-
 PyDoc_STRVAR(index_doc,
 "T.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
 "Raises ValueError if the value is not present."
 );
 PyDoc_STRVAR(count_doc,
 "T.count(value) -> integer -- return number of occurrences of value");
-PyDoc_STRVAR(sizeof_doc,
-"T.__sizeof__() -- size of T in memory, in bytes");
 
 static PyMethodDef tuple_methods[] = {
     {"__getnewargs__",          (PyCFunction)tuple_getnewargs,  METH_NOARGS},
-    {"__sizeof__",      (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc},
     {"index",           (PyCFunction)tupleindex,  METH_VARARGS, index_doc},
     {"count",           (PyCFunction)tuplecount,  METH_O, count_doc},
     {NULL,              NULL}           /* sentinel */
index d0ac3ac..22def74 100644 (file)
@@ -3507,7 +3507,7 @@ object_sizeof(PyObject *self, PyObject *args)
     res = 0;
     isize = self->ob_type->tp_itemsize;
     if (isize > 0)
-        res = self->ob_type->ob_size * isize;
+        res = Py_SIZE(self) * isize;
     res += self->ob_type->tp_basicsize;
 
     return PyInt_FromSsize_t(res);
@@ -4073,6 +4073,23 @@ PyType_Ready(PyTypeObject *type)
             inherit_slots(type, (PyTypeObject *)b);
     }
 
+    /* All bases of statically allocated type should be statically allocated */
+    if (Py_Py3kWarningFlag && !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
+        for (i = 0; i < n; i++) {
+            PyObject *b = PyTuple_GET_ITEM(bases, i);
+            if (PyType_Check(b) &&
+                (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+                char buf[300];
+                PyOS_snprintf(buf, sizeof(buf),
+                              "type '%.100s' is not dynamically allocated but "
+                              "its base type '%.100s' is dynamically allocated",
+                              type->tp_name, ((PyTypeObject *)b)->tp_name);
+                if (PyErr_WarnPy3k(buf, 1) < 0)
+                    goto error;
+                break;
+            }
+        }
+
     /* Sanity check for tp_free. */
     if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
         (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
@@ -4798,7 +4815,7 @@ tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
                      "%s.__new__(%s) is not safe, use %s.__new__()",
                      type->tp_name,
                      subtype->tp_name,
-                     staticbase == NULL ? "?" : staticbase->tp_name);
+                     staticbase->tp_name);
         return NULL;
     }
 
index bdb14d7..91e7524 100644 (file)
@@ -735,15 +735,12 @@ PyUnicode_FromFormatV(const char *format, va_list vargs)
       * objects once during step 3 and put the result in an array) */
     for (f = format; *f; f++) {
          if (*f == '%') {
-             if (*(f+1)=='%')
-                 continue;
-             if (*(f+1)=='S' || *(f+1)=='R')
-                 ++callcount;
-             while (isdigit((unsigned)*f))
-                 width = (width*10) + *f++ - '0';
-             while (*++f && *f != '%' && !isalpha((unsigned)*f))
-                 ;
-             if (*f == 's')
+             f++;
+             while (*f && *f != '%' && !isalpha((unsigned)*f))
+                 f++;
+             if (!*f)
+                 break;
+             if (*f == 's' || *f=='S' || *f=='R')
                  ++callcount;
          }
     }
@@ -760,12 +757,16 @@ PyUnicode_FromFormatV(const char *format, va_list vargs)
     /* step 3: figure out how large a buffer we need */
     for (f = format; *f; f++) {
         if (*f == '%') {
-            const char* p = f;
+            const char* p = f++;
             width = 0;
             while (isdigit((unsigned)*f))
                 width = (width*10) + *f++ - '0';
-            while (*++f && *f != '%' && !isalpha((unsigned)*f))
-                ;
+            precision = 0;
+            if (*f == '.') {
+                f++;
+                while (isdigit((unsigned)*f))
+                    precision = (precision*10) + *f++ - '0';
+            }
 
             /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
              * they don't affect the amount of space we reserve.
@@ -800,6 +801,8 @@ PyUnicode_FromFormatV(const char *format, va_list vargs)
                 break;
             case 'd': case 'u': case 'i': case 'x':
                 (void) va_arg(count, int);
+                if (width < precision)
+                    width = precision;
                 /* 20 bytes is enough to hold a 64-bit
                    integer.  Decimal takes the most space.
                    This isn't enough for octal.
@@ -892,7 +895,8 @@ PyUnicode_FromFormatV(const char *format, va_list vargs)
     }
   expand:
     if (abuffersize > 20) {
-        abuffer = PyObject_Malloc(abuffersize);
+        /* add 1 for sprintf's trailing null byte */
+        abuffer = PyObject_Malloc(abuffersize + 1);
         if (!abuffer) {
             PyErr_NoMemory();
             goto fail;
@@ -2039,7 +2043,7 @@ PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
                see http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
                (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt
                Uncomment the 2 lines below to make them invalid,
-               codepoints: d800-dfff; UTF-8: \xed\xa0\x80-\xed\xbf\xbf. */
+               code points: d800-dfff; UTF-8: \xed\xa0\x80-\xed\xbf\xbf. */
             if ((s[1] & 0xc0) != 0x80 ||
                 (s[2] & 0xc0) != 0x80 ||
                 ((unsigned char)s[0] == 0xE0 &&
@@ -2337,7 +2341,7 @@ PyUnicode_DecodeUTF32Stateful(const char *s,
     }
 
     /* On narrow builds we split characters outside the BMP into two
-       codepoints => count how much extra space we need. */
+       code points => count how much extra space we need. */
 #ifndef Py_UNICODE_WIDE
     for (qq = q; e - qq >= 4; qq += 4)
         if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
@@ -2372,7 +2376,7 @@ PyUnicode_DecodeUTF32Stateful(const char *s,
 
         if (ch >= 0x110000)
         {
-            errmsg = "codepoint not in range(0x110000)";
+            errmsg = "code point not in range(0x110000)";
             startinpos = ((const char *)q)-starts;
             endinpos = startinpos+4;
             goto utf32Error;
@@ -2449,7 +2453,7 @@ PyUnicode_EncodeUTF32(const Py_UNICODE *s,
         p += 4;                                 \
     } while(0)
 
-    /* In narrow builds we can output surrogate pairs as one codepoint,
+    /* In narrow builds we can output surrogate pairs as one code point,
        so we need less space. */
 #ifndef Py_UNICODE_WIDE
     for (i = pairs = 0; i < size-1; i++)
index 871c248..e1f4bc4 100644 (file)
@@ -924,11 +924,9 @@ PyObject_ClearWeakRefs(PyObject *object)
     if (*list != NULL) {
         PyWeakReference *current = *list;
         Py_ssize_t count = _PyWeakref_GetWeakrefCount(current);
-        int restore_error = PyErr_Occurred() ? 1 : 0;
         PyObject *err_type, *err_value, *err_tb;
 
-        if (restore_error)
-            PyErr_Fetch(&err_type, &err_value, &err_tb);
+        PyErr_Fetch(&err_type, &err_value, &err_tb);
         if (count == 1) {
             PyObject *callback = current->wr_callback;
 
@@ -946,8 +944,7 @@ PyObject_ClearWeakRefs(PyObject *object)
 
             tuple = PyTuple_New(count * 2);
             if (tuple == NULL) {
-                if (restore_error)
-                    PyErr_Fetch(&err_type, &err_value, &err_tb);
+                _PyErr_ReplaceException(err_type, err_value, err_tb);
                 return;
             }
 
@@ -978,7 +975,7 @@ PyObject_ClearWeakRefs(PyObject *object)
             }
             Py_DECREF(tuple);
         }
-        if (restore_error)
-            PyErr_Restore(err_type, err_value, err_tb);
+        assert(!PyErr_Occurred());
+        PyErr_Restore(err_type, err_value, err_tb);
     }
 }
index dfdea67..65488b1 100755 (executable)
@@ -1,41 +1,41 @@
-@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.
-@set _exe=python
-@set _qmode=no
-@set _dashO=
-@goto CheckOpts
-:Again
-@shift
-:CheckOpts
-@if "%1"=="-O" set _dashO=-O
-@if "%1"=="-O" goto Again
-@if "%1"=="-q" set _qmode=yes
-@if "%1"=="-q" goto Again
-@if "%1"=="-d" set _exe=python_d
-@if "%1"=="-d" goto Again
-@if "%_qmode%"=="yes" goto Qmode
-@echo Deleting .pyc/.pyo files ...
-@%_exe% rmpyc.py
-%_exe% %_dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9
-@echo About to run again without deleting .pyc/.pyo first:
-@pause
-:Qmode
-%_exe% %_dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9
-@set _exe=
-@set _qmode=
-@set _dashO=
+@rem Run Tests.  Run the regression test suite.\r
+@rem Usage:  rt [-d] [-O] [-q] regrtest_args\r
+@rem -d   Run Debug build (python_d.exe).  Else release build.\r
+@rem -O   Run python.exe or python_d.exe (see -d) with -O.\r
+@rem -q   "quick" -- normally the tests are run twice, the first time\r
+@rem      after deleting all the .py[co] files reachable from Lib/.\r
+@rem      -q runs the tests just once, and without deleting .py[co] files.\r
+@rem All leading instances of these switches are shifted off, and\r
+@rem whatever remains is passed to regrtest.py.  For example,\r
+@rem     rt -O -d -x test_thread\r
+@rem runs\r
+@rem     python_d -O ../../lib/test/regrtest.py -x test_thread\r
+@rem twice, and\r
+@rem     rt -q -g test_binascii\r
+@rem runs\r
+@rem     python_d ../../lib/test/regrtest.py -g test_binascii\r
+@rem to generate the expected-output file for binascii quickly.\r
+@set _exe=python\r
+@set _qmode=no\r
+@set _dashO=\r
+@goto CheckOpts\r
+:Again\r
+@shift\r
+:CheckOpts\r
+@if "%1"=="-O" set _dashO=-O\r
+@if "%1"=="-O" goto Again\r
+@if "%1"=="-q" set _qmode=yes\r
+@if "%1"=="-q" goto Again\r
+@if "%1"=="-d" set _exe=python_d\r
+@if "%1"=="-d" goto Again\r
+@if "%_qmode%"=="yes" goto Qmode\r
+@echo Deleting .pyc/.pyo files ...\r
+@%_exe% rmpyc.py\r
+%_exe% %_dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+@echo About to run again without deleting .pyc/.pyo first:\r
+@pause\r
+:Qmode\r
+%_exe% %_dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+@set _exe=\r
+@set _qmode=\r
+@set _dashO=\r
index fa9acf1..aa77017 100644 (file)
@@ -1,17 +1,17 @@
-@echo off
-rem Try to find the AMD64 assembler and call it with the supplied arguments.
-
-set MLEXE=Microsoft Platform SDK\Bin\Win64\x86\AMD64\ml64.EXE
-
-rem For the environment variables see also
-rem http://msdn.microsoft.com/library/en-us/win64/win64/wow64_implementation_details.asp
-
-if exist "%ProgramFiles%\%MLEXE%" (
-  set ML64="%ProgramFiles%\%MLEXE%"
-) else if exist "%ProgramW6432%\%MLEXE%" (
-  set ML64="%ProgramW6432%\%MLEXE%"
-) else (
-  set ML64=ml64.exe
-)
-
-%ML64% %*
+@echo off\r
+rem Try to find the AMD64 assembler and call it with the supplied arguments.\r
+\r
+set MLEXE=Microsoft Platform SDK\Bin\Win64\x86\AMD64\ml64.EXE\r
+\r
+rem For the environment variables see also\r
+rem http://msdn.microsoft.com/library/en-us/win64/win64/wow64_implementation_details.asp\r
+\r
+if exist "%ProgramFiles%\%MLEXE%" (\r
+  set ML64="%ProgramFiles%\%MLEXE%"\r
+) else if exist "%ProgramW6432%\%MLEXE%" (\r
+  set ML64="%ProgramW6432%\%MLEXE%"\r
+) else (\r
+  set ML64=ml64.exe\r
+)\r
+\r
+%ML64% %*\r
index f6be3c0..9aad441 100644 (file)
@@ -1,12 +1,12 @@
-if "%1" == "ReleaseAMD64" call "%MSSdk%\SetEnv" /XP64 /RETAIL
-
-@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\r
+\r
+@echo off\r
+if not defined HOST_PYTHON (\r
+  if %1 EQU Debug (\r
+    set HOST_PYTHON=python_d.exe\r
+  ) ELSE (\r
+    set HOST_PYTHON=python.exe\r
+  )\r
+)\r
+%HOST_PYTHON% build_ssl.py %1 %2\r
+\r
index 29801d2..2c1a6a7 100755 (executable)
@@ -1,52 +1,52 @@
-@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%;..\..\..\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 -tt ../../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%
-@echo off
-
-echo About to run again without deleting .pyc/.pyo first:
-pause
-
-:Qmode
-echo on
-%cmd%
+@echo off\r
+rem Run Tests.  Run the regression test suite.\r
+rem Usage:  rt [-d] [-O] [-q] regrtest_args\r
+rem -d   Run Debug build (python_d.exe).  Else release build.\r
+rem -O   Run python.exe or python_d.exe (see -d) with -O.\r
+rem -q   "quick" -- normally the tests are run twice, the first time\r
+rem      after deleting all the .py[co] files reachable from Lib/.\r
+rem      -q runs the tests just once, and without deleting .py[co] files.\r
+rem All leading instances of these switches are shifted off, and\r
+rem whatever remains is passed to regrtest.py.  For example,\r
+rem     rt -O -d -x test_thread\r
+rem runs\r
+rem     python_d -O ../../lib/test/regrtest.py -x test_thread\r
+rem twice, and\r
+rem     rt -q -g test_binascii\r
+rem runs\r
+rem     python_d ../../lib/test/regrtest.py -g test_binascii\r
+rem to generate the expected-output file for binascii quickly.\r
+rem\r
+rem Confusing:  if you want to pass a comma-separated list, like\r
+rem     -u network,largefile\r
+rem then you have to quote it on the rt line, like\r
+rem     rt -u "network,largefile"\r
+\r
+setlocal\r
+\r
+set exe=python\r
+set qmode=\r
+set dashO=\r
+PATH %PATH%;..\..\..\tcltk\bin\r
+\r
+:CheckOpts\r
+if "%1"=="-O" (set dashO=-O)     & shift & goto CheckOpts\r
+if "%1"=="-q" (set qmode=yes)    & shift & goto CheckOpts\r
+if "%1"=="-d" (set exe=python_d) & shift & goto CheckOpts\r
+\r
+set cmd=%exe% %dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+if defined qmode goto Qmode\r
+\r
+echo Deleting .pyc/.pyo files ...\r
+%exe% rmpyc.py\r
+\r
+echo on\r
+%cmd%\r
+@echo off\r
+\r
+echo About to run again without deleting .pyc/.pyo first:\r
+pause\r
+\r
+:Qmode\r
+echo on\r
+%cmd%\r
index 9bc8186..a6d961e 100644 (file)
@@ -1,17 +1,17 @@
-@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%
+@echo off\r
+rem A batch program to build or rebuild a particular configuration.\r
+rem just for convenience.\r
+\r
+setlocal\r
+set platf=Win32\r
+set conf=Release\r
+set build=/build\r
+\r
+:CheckOpts\r
+if "%1"=="-c" (set conf=%2)     & shift & shift & goto CheckOpts\r
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts\r
+if "%1"=="-r" (set build=/rebuild)    & shift & goto CheckOpts\r
+\r
+set cmd=devenv pcbuild.sln %build% "%conf%|%platf%"\r
+echo %cmd%\r
+%cmd%\r
index 4c67ae3..01024cf 100644 (file)
@@ -1 +1 @@
-@%comspec% /k env.bat %*
+@%comspec% /k env.bat %*\r
index a37b5bf..d28a767 100644 (file)
@@ -1,41 +1,41 @@
-@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
-
-@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
-
+@echo off\r
+rem A batch program to build PGO (Profile guided optimization) by first\r
+rem building instrumented binaries, then running the testsuite, and\r
+rem finally building the optimized code.\r
+rem Note, after the first instrumented run, one can just keep on\r
+rem building the PGUpdate configuration while developing.\r
+\r
+setlocal\r
+set platf=Win32\r
+\r
+rem use the performance testsuite.  This is quick and simple\r
+set job1=..\..\tools\pybench\pybench.py -n 1 -C 1 --with-gc\r
+set path1=..\..\tools\pybench\r
+\r
+rem or the whole testsuite for more thorough testing\r
+set job2=..\..\lib\test\regrtest.py\r
+set path2=..\..\lib\r
+\r
+set job=%job1%\r
+set clrpath=%path1%\r
+\r
+:CheckOpts\r
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts\r
+if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts\r
+\r
+set PGI=%platf%-pgi\r
+set PGO=%platf%-pgo\r
+\r
+@echo on\r
+rem build the instrumented version\r
+call build -p %platf% -c PGInstrument\r
+\r
+rem remove .pyc files, .pgc files and execute the job\r
+%PGI%\python.exe rmpyc.py %clrpath%\r
+del %PGI%\*.pgc\r
+%PGI%\python.exe %job%\r
+\r
+rem finally build the optimized version\r
+if exist %PGO% del /s /q %PGO%\r
+call build -p %platf% -c PGUpdate\r
+\r
index 2531a5b..f06c2d1 100644 (file)
@@ -1,12 +1,12 @@
-@echo off
-if not defined HOST_PYTHON (
-  if %1 EQU Debug (
-    set HOST_PYTHON=python_d.exe
-    if not exist python27_d.dll exit 1
-  ) ELSE (
-    set HOST_PYTHON=python.exe
-    if not exist python27.dll exit 1
-  )
-)
-%HOST_PYTHON% build_ssl.py %1 %2 %3
-
+@echo off\r
+if not defined HOST_PYTHON (\r
+  if %1 EQU Debug (\r
+    set HOST_PYTHON=python_d.exe\r
+    if not exist python27_d.dll exit 1\r
+  ) ELSE (\r
+    set HOST_PYTHON=python.exe\r
+    if not exist python27.dll exit 1\r
+  )\r
+)\r
+%HOST_PYTHON% build_ssl.py %1 %2 %3\r
+\r
index a4990a8..7717d01 100644 (file)
@@ -1,5 +1,5 @@
-@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
+@echo off\r
+set VS8=%ProgramFiles%\Microsoft Visual Studio 8\r
+echo Build environments: x86, ia64, amd64, x86_amd64, x86_ia64\r
+echo.\r
+call "%VS8%\VC\vcvarsall.bat" %1\r
index 123e704..274ae1a 100644 (file)
@@ -1,15 +1,15 @@
-@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%
+@echo off\r
+rem start idle\r
+rem Usage:  idle [-d]\r
+rem -d   Run Debug build (python_d.exe).  Else release build.\r
+\r
+setlocal\r
+set exe=python\r
+PATH %PATH%;..\..\..\tcltk\bin\r
+\r
+if "%1"=="-d" (set exe=python_d) & shift\r
+\r
+set cmd=%exe% ../../Lib/idlelib/idle.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+\r
+echo on\r
+%cmd%\r
index 767af76..90fd794 100644 (file)
@@ -1,52 +1,52 @@
-@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%;..\..\..\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 -tt ../../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%
-@echo off
-
-echo About to run again without deleting .pyc/.pyo first:
-pause
-
-:Qmode
-echo on
-%cmd%
+@echo off\r
+rem Run Tests.  Run the regression test suite.\r
+rem Usage:  rt [-d] [-O] [-q] regrtest_args\r
+rem -d   Run Debug build (python_d.exe).  Else release build.\r
+rem -O   Run python.exe or python_d.exe (see -d) with -O.\r
+rem -q   "quick" -- normally the tests are run twice, the first time\r
+rem      after deleting all the .py[co] files reachable from Lib/.\r
+rem      -q runs the tests just once, and without deleting .py[co] files.\r
+rem All leading instances of these switches are shifted off, and\r
+rem whatever remains is passed to regrtest.py.  For example,\r
+rem     rt -O -d -x test_thread\r
+rem runs\r
+rem     python_d -O ../lib/test/regrtest.py -x test_thread\r
+rem twice, and\r
+rem     rt -q -g test_binascii\r
+rem runs\r
+rem     python_d ../lib/test/regrtest.py -g test_binascii\r
+rem to generate the expected-output file for binascii quickly.\r
+rem\r
+rem Confusing:  if you want to pass a comma-separated list, like\r
+rem     -u network,largefile\r
+rem then you have to quote it on the rt line, like\r
+rem     rt -u "network,largefile"\r
+\r
+setlocal\r
+\r
+set exe=python\r
+set qmode=\r
+set dashO=\r
+PATH %PATH%;..\..\..\tcltk\bin\r
+\r
+:CheckOpts\r
+if "%1"=="-O" (set dashO=-O)     & shift & goto CheckOpts\r
+if "%1"=="-q" (set qmode=yes)    & shift & goto CheckOpts\r
+if "%1"=="-d" (set exe=python_d) & shift & goto CheckOpts\r
+\r
+set cmd=%exe% %dashO% -E -tt ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+if defined qmode goto Qmode\r
+\r
+echo Deleting .pyc/.pyo files ...\r
+%exe% rmpyc.py\r
+\r
+echo on\r
+%cmd%\r
+@echo off\r
+\r
+echo About to run again without deleting .pyc/.pyo first:\r
+pause\r
+\r
+:Qmode\r
+echo on\r
+%cmd%\r
index 3f55723..ae16097 100644 (file)
@@ -61,7 +61,7 @@ BEGIN
             VALUE "FileDescription", "Python Core\0"
             VALUE "FileVersion", PYTHON_VERSION
             VALUE "InternalName", "Python DLL\0"
-            VALUE "LegalCopyright", "Copyright © 2001-2014 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
+            VALUE "LegalCopyright", "Copyright © 2001-2015 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
index a73560e..fb25879 100644 (file)
@@ -1,18 +1,18 @@
-@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=
-
-: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
-if "%1"=="-d" (set conf=Debug) & shift & goto CheckOpts
-
-set cmd=vcbuild /useenv pcbuild.sln %build% "%conf%|%platf%"
-echo %cmd%
-%cmd%
+@echo off\r
+rem A batch program to build or rebuild a particular configuration.\r
+rem just for convenience.\r
+\r
+setlocal\r
+set platf=Win32\r
+set conf=Release\r
+set build=\r
+\r
+:CheckOpts\r
+if "%1"=="-c" (set conf=%2) & shift & shift & goto CheckOpts\r
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts\r
+if "%1"=="-r" (set build=/rebuild) & shift & goto CheckOpts\r
+if "%1"=="-d" (set conf=Debug) & shift & goto CheckOpts\r
+\r
+set cmd=vcbuild /useenv pcbuild.sln %build% "%conf%|%platf%"\r
+echo %cmd%\r
+%cmd%\r
index 4c67ae3..01024cf 100644 (file)
@@ -1 +1 @@
-@%comspec% /k env.bat %*
+@%comspec% /k env.bat %*\r
index 0c0a473..d7e4e8b 100644 (file)
@@ -1,41 +1,41 @@
-@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
-
-@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
-
+@echo off\r
+rem A batch program to build PGO (Profile guided optimization) by first\r
+rem building instrumented binaries, then running the testsuite, and\r
+rem finally building the optimized code.\r
+rem Note, after the first instrumented run, one can just keep on\r
+rem building the PGUpdate configuration while developing.\r
+\r
+setlocal\r
+set platf=Win32\r
+\r
+rem use the performance testsuite.  This is quick and simple\r
+set job1=..\tools\pybench\pybench.py -n 1 -C 1 --with-gc\r
+set path1=..\tools\pybench\r
+\r
+rem or the whole testsuite for more thorough testing\r
+set job2=..\lib\test\regrtest.py\r
+set path2=..\lib\r
+\r
+set job=%job1%\r
+set clrpath=%path1%\r
+\r
+:CheckOpts\r
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts\r
+if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts\r
+\r
+set PGI=%platf%-pgi\r
+set PGO=%platf%-pgo\r
+\r
+@echo on\r
+rem build the instrumented version\r
+call build -p %platf% -c PGInstrument\r
+\r
+rem remove .pyc files, .pgc files and execute the job\r
+%PGI%\python.exe rmpyc.py %clrpath%\r
+del %PGI%\*.pgc\r
+%PGI%\python.exe %job%\r
+\r
+rem finally build the optimized version\r
+if exist %PGO% del /s /q %PGO%\r
+call build -p %platf% -c PGUpdate\r
+\r
index 2531a5b..f06c2d1 100644 (file)
@@ -1,12 +1,12 @@
-@echo off
-if not defined HOST_PYTHON (
-  if %1 EQU Debug (
-    set HOST_PYTHON=python_d.exe
-    if not exist python27_d.dll exit 1
-  ) ELSE (
-    set HOST_PYTHON=python.exe
-    if not exist python27.dll exit 1
-  )
-)
-%HOST_PYTHON% build_ssl.py %1 %2 %3
-
+@echo off\r
+if not defined HOST_PYTHON (\r
+  if %1 EQU Debug (\r
+    set HOST_PYTHON=python_d.exe\r
+    if not exist python27_d.dll exit 1\r
+  ) ELSE (\r
+    set HOST_PYTHON=python.exe\r
+    if not exist python27.dll exit 1\r
+  )\r
+)\r
+%HOST_PYTHON% build_ssl.py %1 %2 %3\r
+\r
index 3ba2483..dd8bb18 100644 (file)
@@ -158,7 +158,11 @@ def main():
         make_flags = "-a"
     # perl should be on the path, but we also look in "\perl" and "c:\\perl"
     # as "well known" locations
-    perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"])
+    perls = find_all_on_path("perl.exe", [r"\perl\bin",
+                                          r"C:\perl\bin",
+                                          r"\perl64\bin",
+                                          r"C:\perl64\bin",
+                                         ])
     perl = find_working_perl(perls)
     if perl:
         print("Found a working perl at '%s'" % (perl,))
@@ -175,7 +179,8 @@ def main():
         if dir.startswith('nasm'):
             nasm_dir = os.path.join(ssl_dir, os.pardir, dir)
             nasm_dir = os.path.abspath(nasm_dir)
-            os.environ['PATH'] += os.pathsep.join(['', nasm_dir])
+            old_path = os.environ['PATH']
+            os.environ['PATH'] = os.pathsep.join([nasm_dir, old_path])
             break
     else:
         print('NASM was not found, make sure it is on PATH')
index 638b16c..1ba7b6d 100644 (file)
@@ -1,5 +1,5 @@
-@echo off
-set VS9=%ProgramFiles%\Microsoft Visual Studio 9.0
-echo Build environments: x86, ia64, amd64, x86_amd64, x86_ia64
-echo.
-call "%VS9%\VC\vcvarsall.bat" %1
+@echo off\r
+set VS9=%ProgramFiles%\Microsoft Visual Studio 9.0\r
+echo Build environments: x86, ia64, amd64, x86_amd64, x86_ia64\r
+echo.\r
+call "%VS9%\VC\vcvarsall.bat" %1\r
index dcb0485..5ab15f5 100644 (file)
@@ -1,15 +1,15 @@
-@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%
+@echo off\r
+rem start idle\r
+rem Usage:  idle [-d]\r
+rem -d   Run Debug build (python_d.exe).  Else release build.\r
+\r
+setlocal\r
+set exe=python\r
+PATH %PATH%;..\..\tcltk\bin\r
+\r
+if "%1"=="-d" (set exe=python_d) & shift\r
+\r
+set cmd=%exe% ../Lib/idlelib/idle.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+\r
+echo on\r
+%cmd%\r
index aed2300..0af1df7 100644 (file)
@@ -82,7 +82,7 @@
        />\r
        <UserMacro\r
                Name="opensslDir"\r
-               Value="$(externalsDir)\openssl-1.0.1j"\r
+               Value="$(externalsDir)\openssl-1.0.2a"\r
        />\r
        <UserMacro\r
                Name="tcltkDir"\r
index 4d4c7da..71fb021 100644 (file)
-Building Python using VC++ 9.0
-------------------------------
-
-This directory is used to build Python for Win32 and x64 platforms, e.g.
-Windows 2000, XP, Vista and Windows Server 2008.  In order to build 32-bit
-debug and release executables, Microsoft Visual C++ 2008 Express Edition is
-required at the very least.  In order to build 64-bit debug and release
-executables, Visual Studio 2008 Standard Edition is required at the very
-least.  In order to build all of the above, as well as generate release builds
-that make use of Profile Guided Optimisation (PG0), Visual Studio 2008
-Professional Edition is required at the very least.  The official Python
-releases are built with this version of Visual Studio.
-
-For other Windows platforms and compilers, see ../PC/readme.txt.
-
-All you need to do is open the workspace "pcbuild.sln" in Visual Studio,
-select the desired combination of configuration and platform and eventually
-build the solution. Unless you are going to debug a problem in the core or
-you are going to create an optimized build you want to select "Release" as
-configuration.
-
-The PCbuild directory is compatible with all versions of Visual Studio from
-VS C++ Express Edition over the standard edition up to the professional
-edition. However the express edition does not support features like solution
-folders or profile guided optimization (PGO). The missing bits and pieces
-won't stop you from building Python.
-
-The solution is configured to build the projects in the correct order. "Build
-Solution" or F7 takes care of dependencies except for x64 builds. To make
-cross compiling x64 builds on a 32bit OS possible the x64 builds require a
-32bit version of Python.
-
-NOTE:
-   You probably don't want to build most of the other subprojects, unless
-   you're building an entire Python distribution from scratch, or
-   specifically making changes to the subsystems they implement, or are
-   running a Python core buildbot test slave; see SUBPROJECTS below)
-
-When using the Debug setting, the output files have a _d added to
-their name:  python27_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
-land in the amd64 subfolder. The PGI and PGO builds for profile guided
-optimization end up in their own folders, too.
-
-Legacy support
---------------
-
-You can find build directories for older versions of Visual Studio and
-Visual C++ in the PC directory. The legacy build directories are no longer
-actively maintained and may not work out of the box.
-
-PC/VC6/
-    Visual C++ 6.0
-PC/VS7.1/
-    Visual Studio 2003 (7.1)
-PC/VS8.0/
-    Visual Studio 2005 (8.0)
-
-
-C RUNTIME
----------
-
-Visual Studio 2008 uses version 9 of the C runtime (MSVCRT9).  The executables
-are linked to a CRT "side by side" assembly which must be present on the target
-machine.  This is available under the VC/Redist folder of your visual studio
-distribution. On XP and later operating systems that support
-side-by-side assemblies it is not enough to have the msvcrt90.dll present,
-it has to be there as a whole assembly, that is, a folder with the .dll
-and a .manifest.  Also, a check is made for the correct version.
-Therefore, one should distribute this assembly with the dlls, and keep
-it in the same directory.  For compatibility with older systems, one should
-also set the PATH to this directory so that the dll can be found.
-For more info, see the Readme in the VC/Redist folder.
-
-SUBPROJECTS
------------
-These subprojects should build out of the box.  Subprojects other than the
-main ones (pythoncore, python, pythonw) generally build a DLL (renamed to
-.pyd) from a specific module so that users don't have to load the code
-supporting that module unless they import the module.
-
-pythoncore
-    .dll and .lib
-python
-    .exe
-pythonw
-    pythonw.exe, a variant of python.exe that doesn't pop up a DOS box
-_socket
-    socketmodule.c
-_testcapi
-    tests of the Python C API, run via Lib/test/test_capi.py, and
-    implemented by module Modules/_testcapimodule.c
-pyexpat
-    Python wrapper for accelerated XML parsing, which incorporates stable
-    code from the Expat project:  http://sourceforge.net/projects/expat/
-select
-    selectmodule.c
-unicodedata
-    large tables of Unicode data
-winsound
-    play sounds (typically .wav files) under Windows
-
-Python-controlled subprojects that wrap external projects:
-_bsddb
-    Wraps Berkeley DB 4.7.25, which is currently built by _bsddb.vcproj.
-    project.
-_sqlite3
-    Wraps SQLite 3.6.21, which is currently built by sqlite3.vcproj.
-_tkinter
-    Wraps the Tk windowing system.  Unlike _bsddb and _sqlite3, there's no
-    corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's
-    within our pcbuild.sln, which means this module expects to find a
-    pre-built Tcl/Tk in either ..\externals\tcltk for 32-bit or
-    ..\externals\tcltk64 for 64-bit (relative to this directory).  See below
-    for instructions to build Tcl/Tk.
-bz2
-    Python wrapper for the libbz2 compression library.  Homepage
-        http://sources.redhat.com/bzip2/
-    Download the source from the python.org copy into the dist
-    directory:
-
-    svn export http://svn.python.org/projects/external/bzip2-1.0.6
-
-    ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for
-    obtaining external sources then you don't need to manually get the source
-    above via subversion. **
-
-_ssl
-    Python wrapper for the secure sockets library.
-
-    Get the source code through
-
-    svn export http://svn.python.org/projects/external/openssl-1.0.1j
-
-    ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for
-    obtaining external sources then you don't need to manually get the source
-    above via subversion. **
-
-    Alternatively, get the latest version from http://www.openssl.org.
-    You can (theoretically) use any version of OpenSSL you like - the
-    build process will automatically select the latest version.
-
-    You must install the NASM assembler from
-        http://nasm.sf.net
-    for x86 builds.  Put nasm.exe anywhere in your PATH.  If you use the
-    Tools\buildbot\external(-amd64).bat method for getting sources, it also
-    downloads a version of NASM, which the ssl build script will add to PATH.
-
-    You can also install ActivePerl from
-        http://www.activestate.com/activeperl/
-    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 build process makes sure that no patented algorithms are included.
-    For now RC5, MDC2 and IDEA are excluded from the build. You may have
-    to manually remove $(OBJ_D)\i_*.obj from ms\nt.mak if the build process
-    complains about missing files or forbidden IDEA. Again the files provided
-    in the subversion repository are already fixed.
-
-    The MSVC project simply invokes PCBuild/build_ssl.py to perform
-    the build.  This Python script locates and builds your OpenSSL
-    installation, then invokes a simple makefile to build the final .pyd.
-
-    build_ssl.py attempts to catch the most common errors (such as not
-    being able to find OpenSSL sources, or not being able to find a Perl
-    that works with OpenSSL) and give a reasonable error message.
-    If you have a problem that doesn't seem to be handled correctly
-    (eg, you know you have ActivePerl but we can't find it), please take
-    a peek at build_ssl.py and suggest patches.  Note that build_ssl.py
-    should be able to be run directly from the command-line.
-
-    build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do
-    this by hand.
-
-The subprojects above wrap external projects Python doesn't control, and as
-such, a little more work is required in order to download the relevant source
-files for each project before they can be built.  The buildbots do this each
-time they're built, so the easiest approach is to run either external.bat or
-external-amd64.bat in the ..\Tools\buildbot directory from ..\, i.e.:
-
-    C:\..\svn.python.org\projects\python\trunk\PCbuild>cd ..
-    C:\..\svn.python.org\projects\python\trunk>Tools\buildbot\external.bat
-
-This extracts all the external subprojects from http://svn.python.org/external
-via Subversion (so you'll need an svn.exe on your PATH) and places them in
-..\externals (relative to this directory).  The external(-amd64).bat scripts
-will also build a debug build of Tcl/Tk; there aren't any equivalent batch files
-for building release versions of Tcl/Tk lying around in the Tools\buildbot
-directory.  If you need to build a release version of Tcl/Tk it isn't hard
-though, take a look at the relevant external(-amd64).bat file and find the
-two nmake lines, then call each one without the 'DEBUG=1' parameter, i.e.:
-
-The external-amd64.bat file contains this for tcl:
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install
-
-So for a release build, you'd call it as:
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install
-
-    XXX Should we compile with OPTS=threads?
-    XXX Our installer copies a lot of stuff out of the Tcl/Tk install
-    XXX directory.  Is all of that really needed for Python use of Tcl/Tk?
-
-This will be cleaned up in the future; ideally Tcl/Tk will be brought into our
-pcbuild.sln as custom .vcproj files, just as we've recently done with the
-_bsddb.vcproj and sqlite3.vcproj files, which will remove the need for
-Tcl/Tk to be built separately via a batch file.
-
-Building for Itanium
---------------------
-
-Official support for Itanium builds have been dropped from the build. Please
-contact us and provide patches if you are interested in Itanium builds.
-
-Building for AMD64
-------------------
-
-The build process for AMD64 / x64 is very similar to standard builds. You just
-have to set x64 as platform. In addition, the HOST_PYTHON environment variable
-must point to a Python interpreter (at least 2.4), to support cross-compilation.
-
-Building Python Using the free MS Toolkit Compiler
---------------------------------------------------
-
-Microsoft has withdrawn the free MS Toolkit Compiler, so this can no longer
-be considered a supported option. Instead you can use the free VS C++ Express
-Edition.
-
-Profile Guided Optimization
----------------------------
-
-The solution has two configurations for PGO. The PGInstrument
-configuration must be build first. The PGInstrument binaries are
-linked against a profiling library and contain extra debug
-information. The PGUpdate configuration takes the profiling data and
-generates optimized binaries.
-
-The build_pgo.bat script automates the creation of optimized binaries. It
-creates the PGI files, runs the unit test suite or PyBench with the PGI
-python and finally creates the optimized files.
-
-http://msdn.microsoft.com/en-us/library/e7k32f4k(VS.90).aspx
-
-Static library
---------------
-
-The solution has no configuration for static libraries. However it is easy
-it build a static library instead of a DLL. You simply have to set the
-"Configuration Type" to "Static Library (.lib)" and alter the preprocessor
-macro "Py_ENABLE_SHARED" to "Py_NO_ENABLE_SHARED". You may also have to
-change the "Runtime Library" from "Multi-threaded DLL (/MD)" to
-"Multi-threaded (/MT)".
-
-Visual Studio properties
-------------------------
-
-The PCbuild solution makes heavy use of Visual Studio property files
-(*.vsprops). The properties can be viewed and altered in the Property
-Manager (View -> Other Windows -> Property Manager).
-
- * debug (debug macro: _DEBUG)
- * pginstrument (PGO)
- * pgupdate (PGO)
-    +-- pginstrument
- * pyd (python extension, release build)
-    +-- release
-    +-- pyproject
- * pyd_d (python extension, debug build)
-    +-- debug
-    +-- pyproject
- * pyproject (base settings for all projects, user macros like PyDllName)
- * release (release macro: NDEBUG)
- * x64 (AMD64 / x64 platform specific settings)
-
-The pyproject propertyfile defines _WIN32 and x64 defines _WIN64 and _M_X64
-although the macros are set by the compiler, too. The GUI doesn't always know
-about the macros and confuse the user with false information.
-
-YOUR OWN EXTENSION DLLs
------------------------
-
-If you want to create your own extension module DLL, there's an example
-with easy-to-follow instructions in ../PC/example/; read the file
-readme.txt there first.
+Building Python using VC++ 9.0\r
+------------------------------\r
+\r
+This directory is used to build Python for Win32 and x64 platforms, e.g.\r
+Windows 2000, XP, Vista and Windows Server 2008.  In order to build 32-bit\r
+debug and release executables, Microsoft Visual C++ 2008 Express Edition is\r
+required at the very least.  In order to build 64-bit debug and release\r
+executables, Visual Studio 2008 Standard Edition is required at the very\r
+least.  In order to build all of the above, as well as generate release builds\r
+that make use of Profile Guided Optimisation (PG0), Visual Studio 2008\r
+Professional Edition is required at the very least.  The official Python\r
+releases are built with this version of Visual Studio.\r
+\r
+For other Windows platforms and compilers, see ../PC/readme.txt.\r
+\r
+All you need to do is open the workspace "pcbuild.sln" in Visual Studio,\r
+select the desired combination of configuration and platform and eventually\r
+build the solution. Unless you are going to debug a problem in the core or\r
+you are going to create an optimized build you want to select "Release" as\r
+configuration.\r
+\r
+The PCbuild directory is compatible with all versions of Visual Studio from\r
+VS C++ Express Edition over the standard edition up to the professional\r
+edition. However the express edition does not support features like solution\r
+folders or profile guided optimization (PGO). The missing bits and pieces\r
+won't stop you from building Python.\r
+\r
+The solution is configured to build the projects in the correct order. "Build\r
+Solution" or F7 takes care of dependencies except for x64 builds. To make\r
+cross compiling x64 builds on a 32bit OS possible the x64 builds require a\r
+32bit version of Python.\r
+\r
+NOTE:\r
+   You probably don't want to build most of the other subprojects, unless\r
+   you're building an entire Python distribution from scratch, or\r
+   specifically making changes to the subsystems they implement, or are\r
+   running a Python core buildbot test slave; see SUBPROJECTS below)\r
+\r
+When using the Debug setting, the output files have a _d added to\r
+their name:  python27_d.dll, python_d.exe, parser_d.pyd, and so on. Both\r
+the build and rt batch files accept a -d option for debug builds.\r
+\r
+The 32bit builds end up in the solution folder PCbuild while the x64 builds\r
+land in the amd64 subfolder. The PGI and PGO builds for profile guided\r
+optimization end up in their own folders, too.\r
+\r
+Legacy support\r
+--------------\r
+\r
+You can find build directories for older versions of Visual Studio and\r
+Visual C++ in the PC directory. The legacy build directories are no longer\r
+actively maintained and may not work out of the box.\r
+\r
+PC/VC6/\r
+    Visual C++ 6.0\r
+PC/VS7.1/\r
+    Visual Studio 2003 (7.1)\r
+PC/VS8.0/\r
+    Visual Studio 2005 (8.0)\r
+\r
+\r
+C RUNTIME\r
+---------\r
+\r
+Visual Studio 2008 uses version 9 of the C runtime (MSVCRT9).  The executables\r
+are linked to a CRT "side by side" assembly which must be present on the target\r
+machine.  This is available under the VC/Redist folder of your visual studio\r
+distribution. On XP and later operating systems that support\r
+side-by-side assemblies it is not enough to have the msvcrt90.dll present,\r
+it has to be there as a whole assembly, that is, a folder with the .dll\r
+and a .manifest.  Also, a check is made for the correct version.\r
+Therefore, one should distribute this assembly with the dlls, and keep\r
+it in the same directory.  For compatibility with older systems, one should\r
+also set the PATH to this directory so that the dll can be found.\r
+For more info, see the Readme in the VC/Redist folder.\r
+\r
+SUBPROJECTS\r
+-----------\r
+These subprojects should build out of the box.  Subprojects other than the\r
+main ones (pythoncore, python, pythonw) generally build a DLL (renamed to\r
+.pyd) from a specific module so that users don't have to load the code\r
+supporting that module unless they import the module.\r
+\r
+pythoncore\r
+    .dll and .lib\r
+python\r
+    .exe\r
+pythonw\r
+    pythonw.exe, a variant of python.exe that doesn't pop up a DOS box\r
+_socket\r
+    socketmodule.c\r
+_testcapi\r
+    tests of the Python C API, run via Lib/test/test_capi.py, and\r
+    implemented by module Modules/_testcapimodule.c\r
+pyexpat\r
+    Python wrapper for accelerated XML parsing, which incorporates stable\r
+    code from the Expat project:  http://sourceforge.net/projects/expat/\r
+select\r
+    selectmodule.c\r
+unicodedata\r
+    large tables of Unicode data\r
+winsound\r
+    play sounds (typically .wav files) under Windows\r
+\r
+Python-controlled subprojects that wrap external projects:\r
+_bsddb\r
+    Wraps Berkeley DB 4.7.25, which is currently built by _bsddb.vcproj.\r
+    project.\r
+_sqlite3\r
+    Wraps SQLite 3.6.21, which is currently built by sqlite3.vcproj.\r
+_tkinter\r
+    Wraps the Tk windowing system.  Unlike _bsddb and _sqlite3, there's no\r
+    corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's\r
+    within our pcbuild.sln, which means this module expects to find a\r
+    pre-built Tcl/Tk in either ..\externals\tcltk for 32-bit or\r
+    ..\externals\tcltk64 for 64-bit (relative to this directory).  See below\r
+    for instructions to build Tcl/Tk.\r
+bz2\r
+    Python wrapper for the libbz2 compression library.  Homepage\r
+        http://sources.redhat.com/bzip2/\r
+    Download the source from the python.org copy into the dist\r
+    directory:\r
+\r
+    svn export http://svn.python.org/projects/external/bzip2-1.0.6\r
+\r
+    ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for\r
+    obtaining external sources then you don't need to manually get the source\r
+    above via subversion. **\r
+\r
+_ssl\r
+    Python wrapper for the secure sockets library.\r
+\r
+    Get the source code through\r
+\r
+    svn export http://svn.python.org/projects/external/openssl-1.0.2a\r
+\r
+    ** NOTE: if you use the Tools\buildbot\external(-amd64).bat approach for\r
+    obtaining external sources then you don't need to manually get the source\r
+    above via subversion. **\r
+\r
+    The NASM assembler is required to build OpenSSL.  If you use the\r
+    Tools\buildbot\external(-amd64).bat method for getting sources, it also\r
+    downloads a version of NASM, which the ssl build script will add to PATH.\r
+    Otherwise, you can download the NASM installer from\r
+        http://www.nasm.us/\r
+    and add NASM to your PATH.\r
+\r
+    You can also install ActivePerl from\r
+        http://www.activestate.com/activeperl/\r
+    if you like to use the official sources instead of the files from\r
+    python's subversion repository. The svn version contains pre-build\r
+    makefiles and assembly files.\r
+\r
+    The build process makes sure that no patented algorithms are included.\r
+    For now RC5, MDC2 and IDEA are excluded from the build. You may have\r
+    to manually remove $(OBJ_D)\i_*.obj from ms\nt.mak if the build process\r
+    complains about missing files or forbidden IDEA. Again the files provided\r
+    in the subversion repository are already fixed.\r
+\r
+    The MSVC project simply invokes PCBuild/build_ssl.py to perform\r
+    the build.  This Python script locates and builds your OpenSSL\r
+    installation, then invokes a simple makefile to build the final .pyd.\r
+\r
+    build_ssl.py attempts to catch the most common errors (such as not\r
+    being able to find OpenSSL sources, or not being able to find a Perl\r
+    that works with OpenSSL) and give a reasonable error message.\r
+    If you have a problem that doesn't seem to be handled correctly\r
+    (eg, you know you have ActivePerl but we can't find it), please take\r
+    a peek at build_ssl.py and suggest patches.  Note that build_ssl.py\r
+    should be able to be run directly from the command-line.\r
+\r
+    build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do\r
+    this by hand.\r
+\r
+The subprojects above wrap external projects Python doesn't control, and as\r
+such, a little more work is required in order to download the relevant source\r
+files for each project before they can be built.  The buildbots do this each\r
+time they're built, so the easiest approach is to run either external.bat or\r
+external-amd64.bat in the ..\Tools\buildbot directory from ..\, i.e.:\r
+\r
+    C:\..\svn.python.org\projects\python\trunk\PCbuild>cd ..\r
+    C:\..\svn.python.org\projects\python\trunk>Tools\buildbot\external.bat\r
+\r
+This extracts all the external subprojects from http://svn.python.org/external\r
+via Subversion (so you'll need an svn.exe on your PATH) and places them in\r
+..\externals (relative to this directory).  The external(-amd64).bat scripts\r
+will also build a debug build of Tcl/Tk; there aren't any equivalent batch files\r
+for building release versions of Tcl/Tk lying around in the Tools\buildbot\r
+directory.  If you need to build a release version of Tcl/Tk it isn't hard\r
+though, take a look at the relevant external(-amd64).bat file and find the\r
+two nmake lines, then call each one without the 'DEBUG=1' parameter, i.e.:\r
+\r
+The external-amd64.bat file contains this for tcl:\r
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install\r
+\r
+So for a release build, you'd call it as:\r
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all install\r
+\r
+    XXX Should we compile with OPTS=threads?\r
+    XXX Our installer copies a lot of stuff out of the Tcl/Tk install\r
+    XXX directory.  Is all of that really needed for Python use of Tcl/Tk?\r
+\r
+This will be cleaned up in the future; ideally Tcl/Tk will be brought into our\r
+pcbuild.sln as custom .vcproj files, just as we've recently done with the\r
+_bsddb.vcproj and sqlite3.vcproj files, which will remove the need for\r
+Tcl/Tk to be built separately via a batch file.\r
+\r
+Building for Itanium\r
+--------------------\r
+\r
+Official support for Itanium builds have been dropped from the build. Please\r
+contact us and provide patches if you are interested in Itanium builds.\r
+\r
+Building for AMD64\r
+------------------\r
+\r
+The build process for AMD64 / x64 is very similar to standard builds. You just\r
+have to set x64 as platform. In addition, the HOST_PYTHON environment variable\r
+must point to a Python interpreter (at least 2.4), to support cross-compilation.\r
+\r
+Building Python Using the free MS Toolkit Compiler\r
+--------------------------------------------------\r
+\r
+Microsoft has withdrawn the free MS Toolkit Compiler, so this can no longer\r
+be considered a supported option. Instead you can use the free VS C++ Express\r
+Edition.\r
+\r
+Profile Guided Optimization\r
+---------------------------\r
+\r
+The solution has two configurations for PGO. The PGInstrument\r
+configuration must be build first. The PGInstrument binaries are\r
+linked against a profiling library and contain extra debug\r
+information. The PGUpdate configuration takes the profiling data and\r
+generates optimized binaries.\r
+\r
+The build_pgo.bat script automates the creation of optimized binaries. It\r
+creates the PGI files, runs the unit test suite or PyBench with the PGI\r
+python and finally creates the optimized files.\r
+\r
+http://msdn.microsoft.com/en-us/library/e7k32f4k(VS.90).aspx\r
+\r
+Static library\r
+--------------\r
+\r
+The solution has no configuration for static libraries. However it is easy\r
+it build a static library instead of a DLL. You simply have to set the\r
+"Configuration Type" to "Static Library (.lib)" and alter the preprocessor\r
+macro "Py_ENABLE_SHARED" to "Py_NO_ENABLE_SHARED". You may also have to\r
+change the "Runtime Library" from "Multi-threaded DLL (/MD)" to\r
+"Multi-threaded (/MT)".\r
+\r
+Visual Studio properties\r
+------------------------\r
+\r
+The PCbuild solution makes heavy use of Visual Studio property files\r
+(*.vsprops). The properties can be viewed and altered in the Property\r
+Manager (View -> Other Windows -> Property Manager).\r
+\r
+ * debug (debug macro: _DEBUG)\r
+ * pginstrument (PGO)\r
+ * pgupdate (PGO)\r
+    +-- pginstrument\r
+ * pyd (python extension, release build)\r
+    +-- release\r
+    +-- pyproject\r
+ * pyd_d (python extension, debug build)\r
+    +-- debug\r
+    +-- pyproject\r
+ * pyproject (base settings for all projects, user macros like PyDllName)\r
+ * release (release macro: NDEBUG)\r
+ * x64 (AMD64 / x64 platform specific settings)\r
+\r
+The pyproject propertyfile defines _WIN32 and x64 defines _WIN64 and _M_X64\r
+although the macros are set by the compiler, too. The GUI doesn't always know\r
+about the macros and confuse the user with false information.\r
+\r
+YOUR OWN EXTENSION DLLs\r
+-----------------------\r
+\r
+If you want to create your own extension module DLL, there's an example\r
+with easy-to-follow instructions in ../PC/example/; read the file\r
+readme.txt there first.\r
index 12ea6eb..ebe88a2 100644 (file)
@@ -1,58 +1,58 @@
-@echo off
-rem Run Tests.  Run the regression test suite.
-rem Usage:  rt [-d] [-O] [-q] [-x64] 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 -x64 Run the 64-bit build of python (or python_d if -d was specified)
-rem      from the 'amd64' dir instead of the 32-bit build in this dir.
-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 prefix=.\
-set suffix=
-set qmode=
-set dashO=
-set tcltk=tcltk
-
-:CheckOpts
-if "%1"=="-O" (set dashO=-O)     & shift & goto CheckOpts
-if "%1"=="-q" (set qmode=yes)    & shift & goto CheckOpts
-if "%1"=="-d" (set suffix=_d)    & shift & goto CheckOpts
-if "%1"=="-x64" (set prefix=amd64) & (set tcltk=tcltk64) & shift & goto CheckOpts
-
-PATH %PATH%;%~dp0..\externals\%tcltk%\bin
-set exe=%prefix%\python%suffix%
-set cmd=%exe% %dashO% -Wd -3 -E -tt ../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%
-@echo off
-
-echo About to run again without deleting .pyc/.pyo first:
-pause
-
-:Qmode
-echo on
-%cmd%
+@echo off\r
+rem Run Tests.  Run the regression test suite.\r
+rem Usage:  rt [-d] [-O] [-q] [-x64] regrtest_args\r
+rem -d   Run Debug build (python_d.exe).  Else release build.\r
+rem -O   Run python.exe or python_d.exe (see -d) with -O.\r
+rem -q   "quick" -- normally the tests are run twice, the first time\r
+rem      after deleting all the .py[co] files reachable from Lib/.\r
+rem      -q runs the tests just once, and without deleting .py[co] files.\r
+rem -x64 Run the 64-bit build of python (or python_d if -d was specified)\r
+rem      from the 'amd64' dir instead of the 32-bit build in this dir.\r
+rem All leading instances of these switches are shifted off, and\r
+rem whatever remains is passed to regrtest.py.  For example,\r
+rem     rt -O -d -x test_thread\r
+rem runs\r
+rem     python_d -O ../lib/test/regrtest.py -x test_thread\r
+rem twice, and\r
+rem     rt -q -g test_binascii\r
+rem runs\r
+rem     python_d ../lib/test/regrtest.py -g test_binascii\r
+rem to generate the expected-output file for binascii quickly.\r
+rem\r
+rem Confusing:  if you want to pass a comma-separated list, like\r
+rem     -u network,largefile\r
+rem then you have to quote it on the rt line, like\r
+rem     rt -u "network,largefile"\r
+\r
+setlocal\r
+\r
+set prefix=.\\r
+set suffix=\r
+set qmode=\r
+set dashO=\r
+set tcltk=tcltk\r
+\r
+:CheckOpts\r
+if "%1"=="-O" (set dashO=-O)     & shift & goto CheckOpts\r
+if "%1"=="-q" (set qmode=yes)    & shift & goto CheckOpts\r
+if "%1"=="-d" (set suffix=_d)    & shift & goto CheckOpts\r
+if "%1"=="-x64" (set prefix=amd64) & (set tcltk=tcltk64) & shift & goto CheckOpts\r
+\r
+PATH %PATH%;%~dp0..\externals\%tcltk%\bin\r
+set exe=%prefix%\python%suffix%\r
+set cmd=%exe% %dashO% -Wd -3 -E -tt ../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9\r
+if defined qmode goto Qmode\r
+\r
+echo Deleting .pyc/.pyo files ...\r
+%exe% rmpyc.py\r
+\r
+echo on\r
+%cmd%\r
+@echo off\r
+\r
+echo About to run again without deleting .pyc/.pyo first:\r
+pause\r
+\r
+:Qmode\r
+echo on\r
+%cmd%\r
index 682a1e7..fa6bb60 100644 (file)
@@ -66,9 +66,11 @@ ppc_getcounter(uint64 *v)
    even in 64-bit mode, we need to use "a" and "d" for the lower and upper
    32-bit pieces of the result. */
 
-#define READ_TIMESTAMP(val) \
-    __asm__ __volatile__("rdtsc" : \
-                         "=a" (((int*)&(val))[0]), "=d" (((int*)&(val))[1]));
+#define READ_TIMESTAMP(val) do {                        \
+    unsigned int h, l;                                  \
+    __asm__ __volatile__("rdtsc" : "=a" (l), "=d" (h)); \
+    (val) = ((uint64)l) | (((uint64)h) << 32);          \
+    } while(0)
 
 
 #else
index 9d9e629..1f59c8c 100644 (file)
@@ -1716,10 +1716,9 @@ compiler_while(struct compiler *c, stmt_ty s)
        if there is no else clause ?
     */
 
-    if (constant == -1) {
+    if (constant == -1)
         compiler_use_next_block(c, anchor);
-        ADDOP(c, POP_BLOCK);
-    }
+    ADDOP(c, POP_BLOCK);
     compiler_pop_fblock(c, LOOP, loop);
     if (orelse != NULL) /* what if orelse is just pass? */
         VISIT_SEQ(c, stmt, s->v.While.orelse);
index 64ba05d..00dfd3e 100644 (file)
@@ -263,6 +263,26 @@ PyErr_Clear(void)
     PyErr_Restore(NULL, NULL, NULL);
 }
 
+/* Restore previously fetched exception if an exception is not set,
+   otherwise drop previously fetched exception.
+   Like _PyErr_ChainExceptions() in Python 3, but doesn't set the context.
+ */
+void
+_PyErr_ReplaceException(PyObject *exc, PyObject *val, PyObject *tb)
+{
+    if (exc == NULL)
+        return;
+
+    if (PyErr_Occurred()) {
+        Py_DECREF(exc);
+        Py_XDECREF(val);
+        Py_XDECREF(tb);
+    }
+    else {
+        PyErr_Restore(exc, val, tb);
+    }
+}
+
 /* Convenience functions to set a type error exception and return 0 */
 
 int
index d31da07..e742172 100644 (file)
@@ -35,7 +35,8 @@ Py_FrozenMain(int argc, char **argv)
 #ifdef MS_WINDOWS
     PyInitFrozenExtensions();
 #endif /* MS_WINDOWS */
-    Py_SetProgramName(argv[0]);
+    if (argc >= 1)
+        Py_SetProgramName(argv[0]);
     Py_Initialize();
 #ifdef MS_WINDOWS
     PyWinFreeze_ExeInit();
index 629a240..913e1d2 100644 (file)
@@ -4,7 +4,7 @@
 
 static char cprt[] = 
 "\
-Copyright (c) 2001-2014 Python Software Foundation.\n\
+Copyright (c) 2001-2015 Python Software Foundation.\n\
 All Rights Reserved.\n\
 \n\
 Copyright (c) 2000 BeOpen.com.\n\
index 92363b3..e47ce63 100644 (file)
@@ -337,8 +337,12 @@ _PyImport_ReleaseLock(void)
 void
 _PyImport_ReInitLock(void)
 {
-    if (import_lock != NULL)
+    if (import_lock != NULL) {
         import_lock = PyThread_allocate_lock();
+        if (import_lock == NULL) {
+            Py_FatalError("PyImport_ReInitLock failed to create a new lock");
+        }
+    }
     import_lock_thread = -1;
     import_lock_level = 0;
 }
index fb6cd03..e3bc004 100644 (file)
@@ -242,7 +242,7 @@ fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
 static unsigned int *
 markblocks(unsigned char *code, Py_ssize_t len)
 {
-    unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
+    unsigned int *blocks = PyMem_New(unsigned int, len);
     int i,j, opcode, blockcnt = 0;
 
     if (blocks == NULL) {
@@ -343,9 +343,11 @@ PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
         goto exitUnchanged;
 
     /* Mapping to new jump targets after NOPs are removed */
-    addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
-    if (addrmap == NULL)
+    addrmap = PyMem_New(int, codelen);
+    if (addrmap == NULL) {
+        PyErr_NoMemory();
         goto exitError;
+    }
 
     blocks = markblocks(codestr, codelen);
     if (blocks == NULL)
index 859af43..ae6ab9c 100644 (file)
@@ -324,7 +324,7 @@ PyOS_ascii_atof(const char *nptr)
 
    On overflow (e.g., when trying to convert '1e500' on an IEEE 754 machine),
    if overflow_exception is NULL then +-Py_HUGE_VAL is returned, and no Python
-   exception is raised.  Otherwise, overflow_exception should point to a
+   exception is raised.  Otherwise, overflow_exception should point to
    a Python exception, this exception will be raised, -1.0 will be returned,
    and *endptr will point just past the end of the converted value.
 
index 0776bfc..d94f89a 100644 (file)
@@ -92,8 +92,41 @@ win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
     }
     return 0;
 }
-#endif /* MS_WINDOWS */
 
+#elif HAVE_GETENTROPY
+/* Fill buffer with size pseudo-random bytes generated by getentropy().
+   Return 0 on success, or raise an exception and return -1 on error.
+   If fatal is nonzero, call Py_FatalError() instead of raising an exception
+   on error. */
+static int
+py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
+{
+    while (size > 0) {
+        Py_ssize_t len = size < 256 ? size : 256;
+        int res;
+
+        if (!fatal) {
+            Py_BEGIN_ALLOW_THREADS
+            res = getentropy(buffer, len);
+            Py_END_ALLOW_THREADS
+
+            if (res < 0) {
+                PyErr_SetFromErrno(PyExc_OSError);
+                return -1;
+            }
+        }
+        else {
+            res = getentropy(buffer, len);
+            if (res < 0)
+                Py_FatalError("getentropy() failed");
+        }
+
+        buffer += len;
+        size -= len;
+    }
+    return 0;
+}
+#endif
 
 #ifdef __VMS
 /* Use openssl random routine */
@@ -163,6 +196,7 @@ dev_urandom_python(char *buffer, Py_ssize_t size)
     int fd;
     Py_ssize_t n;
     struct stat st;
+    int attr;
 
     if (size <= 0)
         return 0;
@@ -194,6 +228,14 @@ dev_urandom_python(char *buffer, Py_ssize_t size)
                 PyErr_SetFromErrno(PyExc_OSError);
             return -1;
         }
+
+        /* try to make the file descriptor non-inheritable, ignore errors */
+        attr = fcntl(fd, F_GETFD);
+        if (attr >= 0) {
+            attr |= FD_CLOEXEC;
+            (void)fcntl(fd, F_SETFD, attr);
+        }
+
         if (urandom_cache.fd >= 0) {
             /* urandom_fd was initialized by another thread while we were
                not holding the GIL, keep it. */
@@ -274,7 +316,7 @@ lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
 }
 
 /* Fill buffer with size pseudo-random bytes from the operating system random
-   number generator (RNG). It is suitable for for most cryptographic purposes
+   number generator (RNG). It is suitable for most cryptographic purposes
    except long living private keys for asymmetric encryption.
 
    Return 0 on success, raise an exception and return -1 on error. */
@@ -291,6 +333,8 @@ _PyOS_URandom(void *buffer, Py_ssize_t size)
 
 #ifdef MS_WINDOWS
     return win32_urandom((unsigned char *)buffer, size, 1);
+#elif HAVE_GETENTROPY
+    return py_getentropy(buffer, size, 0);
 #else
 # ifdef __VMS
     return vms_urandom((unsigned char *)buffer, size, 1);
@@ -350,12 +394,12 @@ _PyRandom_Init(void)
     else {
 #ifdef MS_WINDOWS
         (void)win32_urandom((unsigned char *)secret, secret_size, 0);
-#else /* #ifdef MS_WINDOWS */
-# ifdef __VMS
+#elif __VMS
         vms_urandom((unsigned char *)secret, secret_size, 0);
-# else
-        dev_urandom_noraise((unsigned char*)secret, secret_size);
-# endif
+#elif HAVE_GETENTROPY
+        (void)py_getentropy(secret, secret_size, 1);
+#else
+        dev_urandom_noraise(secret, secret_size);
 #endif
     }
 }
@@ -368,6 +412,8 @@ _PyRandom_Fini(void)
         CryptReleaseContext(hCryptProv, 0);
         hCryptProv = 0;
     }
+#elif HAVE_GETENTROPY
+    /* nothing to clean */
 #else
     dev_urandom_close();
 #endif
index dd333e8..c54670d 100644 (file)
@@ -271,7 +271,7 @@ find_key(int key, void *value)
         if (p->id == id && p->key == key)
             goto Done;
         /* Sanity check.  These states should never happen but if
-         * they do we must abort.  Otherwise we'll end up spinning in
+         * they do we must abort.  Otherwise we'll end up spinning
          * in a tight loop with the lock held.  A similar check is done
          * in pystate.c tstate_delete_common().  */
         if (p == prev_p)
diff --git a/README b/README
index 1d5b650..252d90e 100644 (file)
--- a/README
+++ b/README
@@ -1,8 +1,8 @@
-This is Python version 2.7.9
-============================
+This is Python version 2.7.10
+=============================
 
 Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013, 2014 Python Software Foundation.  All rights reserved.
+2012, 2013, 2014, 2015 Python Software Foundation.  All rights reserved.
 
 Copyright (c) 2000 BeOpen.com.
 All rights reserved.
index 8713b38..b5b10d6 100644 (file)
@@ -1,7 +1,7 @@
-@rem Used by the buildbot "compile" step.
-set HOST_PYTHON="%CD%\PCbuild\amd64\python_d.exe"
-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"
+@rem Used by the buildbot "compile" step.\r
+set HOST_PYTHON="%CD%\PCbuild\amd64\python_d.exe"\r
+cmd /c Tools\buildbot\external-amd64.bat\r
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64\r
+cmd /c Tools\buildbot\clean-amd64.bat\r
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|x64" && PCbuild\amd64\kill_python_d.exe\r
+vcbuild PCbuild\pcbuild.sln "Debug|x64"\r
index ab3ea7d..976ce72 100644 (file)
@@ -1,7 +1,7 @@
-@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"
-
+@rem Used by the buildbot "compile" step.\r
+cmd /c Tools\buildbot\external.bat\r
+call "%VS90COMNTOOLS%vsvars32.bat"\r
+cmd /c Tools\buildbot\clean.bat\r
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|Win32" && PCbuild\kill_python_d.exe\r
+vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32"\r
+\r
index a0f43a6..b4f63dc 100644 (file)
@@ -1,20 +1,20 @@
-@rem Used by the buildbot "buildmsi" step.
-
-cmd /c Tools\buildbot\external.bat
-@rem build release versions of things
-call "%VS90COMNTOOLS%vsvars32.bat"
-
-@rem build Python
-vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"
-
-@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
-
-@rem build the MSI file
-cd PC
-nmake /f icons.mak
-cd ..\Tools\msi
-del *.msi
-nmake /f msisupport.mak
-%HOST_PYTHON% msi.py
+@rem Used by the buildbot "buildmsi" step.\r
+\r
+cmd /c Tools\buildbot\external.bat\r
+@rem build release versions of things\r
+call "%VS90COMNTOOLS%vsvars32.bat"\r
+\r
+@rem build Python\r
+vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"\r
+\r
+@rem build the documentation\r
+bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp'\r
+"%ProgramFiles%\HTML Help Workshop\hhc.exe" Doc\build\htmlhelp\python26a3.hhp\r
+\r
+@rem build the MSI file\r
+cd PC\r
+nmake /f icons.mak\r
+cd ..\Tools\msi\r
+del *.msi\r
+nmake /f msisupport.mak\r
+%HOST_PYTHON% msi.py\r
index 715805a..0f6b3b4 100644 (file)
@@ -1,10 +1,10 @@
-@rem Used by the buildbot "clean" step.
-call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
-@echo Deleting .pyc/.pyo files ...
-del /s Lib\*.pyc Lib\*.pyo
-@echo Deleting test leftovers ...
-rmdir /s /q build
-cd PCbuild
-vcbuild /clean pcbuild.sln "Release|x64"
-vcbuild /clean pcbuild.sln "Debug|x64"
-cd ..
+@rem Used by the buildbot "clean" step.\r
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64\r
+@echo Deleting .pyc/.pyo files ...\r
+del /s Lib\*.pyc Lib\*.pyo\r
+@echo Deleting test leftovers ...\r
+rmdir /s /q build\r
+cd PCbuild\r
+vcbuild /clean pcbuild.sln "Release|x64"\r
+vcbuild /clean pcbuild.sln "Debug|x64"\r
+cd ..\r
index 5c8f33e..cf8a6b7 100644 (file)
@@ -1,10 +1,10 @@
-@rem Used by the buildbot "clean" step.
-call "%VS90COMNTOOLS%vsvars32.bat"
-@echo Deleting .pyc/.pyo files ...
-del /s Lib\*.pyc Lib\*.pyo
-@echo Deleting test leftovers ...
-rmdir /s /q build
-cd PCbuild
-vcbuild /clean pcbuild.sln "Release|Win32"
-vcbuild /clean pcbuild.sln "Debug|Win32"
-cd ..
+@rem Used by the buildbot "clean" step.\r
+call "%VS90COMNTOOLS%vsvars32.bat"\r
+@echo Deleting .pyc/.pyo files ...\r
+del /s Lib\*.pyc Lib\*.pyo\r
+@echo Deleting test leftovers ...\r
+rmdir /s /q build\r
+cd PCbuild\r
+vcbuild /clean pcbuild.sln "Release|Win32"\r
+vcbuild /clean pcbuild.sln "Debug|Win32"\r
+cd ..\r
index e6bc993..16fc405 100644 (file)
@@ -1,28 +1,28 @@
-@rem Fetches (and builds if necessary) external dependencies
-
-@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.15.0\win
-    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all
-    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 install
-    cd ..\..
-)
-
-if not exist tcltk64\bin\tk85g.dll (
-    cd tk-8.5.15.0\win
-    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 clean
-    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 all
-    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 install
-    cd ..\..
-)
-
-if not exist tcltk64\lib\tix8.4.3\tix84g.dll (
-    cd tix-8.4.3.5\win
-    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 clean
-    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 all
-    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 install
-    cd ..\..
-)
+@rem Fetches (and builds if necessary) external dependencies\r
+\r
+@rem Assume we start inside the Python source directory\r
+call "Tools\buildbot\external-common.bat"\r
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64\r
+\r
+if not exist tcltk64\bin\tcl85g.dll (\r
+    cd tcl-8.5.15.0\win\r
+    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all\r
+    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 install\r
+    cd ..\..\r
+)\r
+\r
+if not exist tcltk64\bin\tk85g.dll (\r
+    cd tk-8.5.15.0\win\r
+    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 clean\r
+    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 all\r
+    nmake -f makefile.vc DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.15.0 install\r
+    cd ..\..\r
+)\r
+\r
+if not exist tcltk64\lib\tix8.4.3\tix84g.dll (\r
+    cd tix-8.4.3.5\win\r
+    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 clean\r
+    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 all\r
+    nmake -f python.mak DEBUG=1 MACHINE=AMD64 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk64 install\r
+    cd ..\..\r
+)\r
index fb36c17..12e2517 100644 (file)
@@ -1,61 +1,65 @@
-@rem Common file shared between external.bat and external-amd64.bat.  Responsible for
-@rem fetching external components into the root\externals directory.
-
-if not exist externals mkdir externals
-cd externals
-@rem XXX: If you need to force the buildbots to start from a fresh environment, uncomment
-@rem the following, check it in, then check it out, comment it out, then check it back in.
-@rem if exist bzip2-1.0.6 rd /s/q bzip2-1.0.6
-@rem if exist tcltk rd /s/q tcltk
-@rem if exist tcltk64 rd /s/q tcltk64
-@rem if exist tcl8.4.12 rd /s/q tcl8.4.12
-@rem if exist tcl8.4.16 rd /s/q tcl8.4.16
-@rem if exist tcl-8.4.18.1 rd /s/q tcl-8.4.18.1
-@rem if exist tcl-8.5.2.1 rd /s/q tcl-8.5.2.1
-@rem if exist tcl-8.5.15.0 rd /s/q tcl-8.5.15.0
-@rem if exist tk8.4.12 rd /s/q tk8.4.12
-@rem if exist tk8.4.16 rd /s/q tk8.4.16
-@rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1
-@rem if exist tk-8.5.2.0 rd /s/q tk-8.5.2.0
-@rem if exist tk-8.5.15.0 rd /s/q tk-8.5.15.0
-@rem if exist tix-8.4.3.5 rd /s/q tix-8.4.3.5
-@rem if exist db-4.4.20 rd /s/q db-4.4.20
-@rem if exist db-4.7.25.0 rd /s/q db-4.7.25.0
-@rem if exist openssl-0.9.8y rd /s/q openssl-0.9.8y
-@rem if exist openssl-1.0.1g rd /s/q openssl-1.0.1g
-@rem if exist openssl-1.0.1h rd /s/q openssl-1.0.1h
-@rem if exist openssl-1.0.1i rd /s/q openssl-1.0.1i
-@rem if exist openssl-1.0.1j rd /s/q openssl-1.0.1j
-@rem if exist sqlite-3.6.21 rd /s/q sqlite-3.6.21
-
-@rem bzip
-if not exist bzip2-1.0.6 (
-   rd /s/q bzip2-1.0.5
-  svn export http://svn.python.org/projects/external/bzip2-1.0.6
-)
-
-@rem Berkeley DB
-if exist db-4.4.20 rd /s/q db-4.4.20
-if not exist db-4.7.25.0 svn export http://svn.python.org/projects/external/db-4.7.25.0
-
-@rem NASM, for OpenSSL build
-@rem if exist nasm-2.11.06 rd /s/q nasm-2.11.06
-if not exist nasm-2.11.06 svn export http://svn.python.org/projects/external/nasm-2.11.06
-
-@rem OpenSSL
-if exist openssl-1.0.1i rd /s/q openssl-1.0.1i
-if not exist openssl-1.0.1j svn export http://svn.python.org/projects/external/openssl-1.0.1j
-
-@rem tcl/tk
-if not exist tcl-8.5.15.0 (
-   rd /s/q tcltk tcltk64 tcl-8.5.2.1 tk-8.5.2.0
-   svn export http://svn.python.org/projects/external/tcl-8.5.15.0
-)
-if not exist tk-8.5.15.0 svn export http://svn.python.org/projects/external/tk-8.5.15.0
-if not exist tix-8.4.3.5 svn export http://svn.python.org/projects/external/tix-8.4.3.5
-
-@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
-)
+@rem Common file shared between external.bat and external-amd64.bat.  Responsible for\r
+@rem fetching external components into the root\externals directory.\r
+\r
+if "%SVNROOT%"=="" set SVNROOT=http://svn.python.org/projects/external/\r
+\r
+if not exist externals mkdir externals\r
+cd externals\r
+@rem XXX: If you need to force the buildbots to start from a fresh environment, uncomment\r
+@rem the following, check it in, then check it out, comment it out, then check it back in.\r
+@rem if exist bzip2-1.0.6 rd /s/q bzip2-1.0.6\r
+@rem if exist tcltk rd /s/q tcltk\r
+@rem if exist tcltk64 rd /s/q tcltk64\r
+@rem if exist tcl8.4.12 rd /s/q tcl8.4.12\r
+@rem if exist tcl8.4.16 rd /s/q tcl8.4.16\r
+@rem if exist tcl-8.4.18.1 rd /s/q tcl-8.4.18.1\r
+@rem if exist tcl-8.5.2.1 rd /s/q tcl-8.5.2.1\r
+@rem if exist tcl-8.5.15.0 rd /s/q tcl-8.5.15.0\r
+@rem if exist tk8.4.12 rd /s/q tk8.4.12\r
+@rem if exist tk8.4.16 rd /s/q tk8.4.16\r
+@rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1\r
+@rem if exist tk-8.5.2.0 rd /s/q tk-8.5.2.0\r
+@rem if exist tk-8.5.15.0 rd /s/q tk-8.5.15.0\r
+@rem if exist tix-8.4.3.5 rd /s/q tix-8.4.3.5\r
+@rem if exist db-4.4.20 rd /s/q db-4.4.20\r
+@rem if exist db-4.7.25.0 rd /s/q db-4.7.25.0\r
+@rem if exist openssl-0.9.8y rd /s/q openssl-0.9.8y\r
+@rem if exist openssl-1.0.1g rd /s/q openssl-1.0.1g\r
+@rem if exist openssl-1.0.1h rd /s/q openssl-1.0.1h\r
+@rem if exist openssl-1.0.1i rd /s/q openssl-1.0.1i\r
+@rem if exist openssl-1.0.1j rd /s/q openssl-1.0.1j\r
+@rem if exist openssl-1.0.1l rd /s/q openssl-1.0.1l\r
+@rem if exist openssl-1.0.2a rd /s/q openssl-1.0.2a\r
+@rem if exist sqlite-3.6.21 rd /s/q sqlite-3.6.21\r
+\r
+@rem bzip\r
+if not exist bzip2-1.0.6 (\r
+   rd /s/q bzip2-1.0.5\r
+  svn export %SVNROOT%bzip2-1.0.6\r
+)\r
+\r
+@rem Berkeley DB\r
+if exist db-4.4.20 rd /s/q db-4.4.20\r
+if not exist db-4.7.25.0 svn export %SVNROOT%db-4.7.25.0\r
+\r
+@rem NASM, for OpenSSL build\r
+@rem if exist nasm-2.11.06 rd /s/q nasm-2.11.06\r
+if not exist nasm-2.11.06 svn export %SVNROOT%nasm-2.11.06\r
+\r
+@rem OpenSSL\r
+if exist openssl-1.0.1l rd /s/q openssl-1.0.1l\r
+if not exist openssl-1.0.2a svn export %SVNROOT%openssl-1.0.2a\r
+\r
+@rem tcl/tk\r
+if not exist tcl-8.5.15.0 (\r
+   rd /s/q tcltk tcltk64 tcl-8.5.2.1 tk-8.5.2.0\r
+   svn export %SVNROOT%tcl-8.5.15.0\r
+)\r
+if not exist tk-8.5.15.0 svn export %SVNROOT%tk-8.5.15.0\r
+if not exist tix-8.4.3.5 svn export %SVNROOT%tix-8.4.3.5\r
+\r
+@rem sqlite3\r
+if not exist sqlite-3.6.21 (\r
+  rd /s/q sqlite-source-3.3.4\r
+  svn export %SVNROOT%sqlite-3.6.21\r
+)\r
index 8aaaf46..416d5f3 100644 (file)
@@ -1,29 +1,29 @@
-@rem Fetches (and builds if necessary) external dependencies
-
-@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.15.0\win
-    nmake -f makefile.vc 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.15.0\win
-    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 clean
-    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 all
-    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 install
-    cd ..\..
-)
-
-if not exist tcltk\lib\tix8.4.3\tix84g.dll (
-    cd tix-8.4.3.5\win
-    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk clean
-    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk all
-    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk install
-    cd ..\..
-)
+@rem Fetches (and builds if necessary) external dependencies\r
+\r
+@rem Assume we start inside the Python source directory\r
+call "Tools\buildbot\external-common.bat"\r
+call "%VS90COMNTOOLS%\vsvars32.bat"\r
+\r
+if not exist tcltk\bin\tcl85g.dll (\r
+    @rem all and install need to be separate invocations, otherwise nmakehlp is not found on install\r
+    cd tcl-8.5.15.0\win\r
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk clean all\r
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk install\r
+    cd ..\..\r
+)\r
+\r
+if not exist tcltk\bin\tk85g.dll (\r
+    cd tk-8.5.15.0\win\r
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 clean\r
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 all\r
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.15.0 install\r
+    cd ..\..\r
+)\r
+\r
+if not exist tcltk\lib\tix8.4.3\tix84g.dll (\r
+    cd tix-8.4.3.5\win\r
+    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk clean\r
+    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk all\r
+    nmake -f python.mak DEBUG=1 MACHINE=IX86 TCL_DIR=..\..\tcl-8.5.15.0 TK_DIR=..\..\tk-8.5.15.0 INSTALL_DIR=..\..\tcltk install\r
+    cd ..\..\r
+)\r
index 0003761..c6cfae5 100644 (file)
@@ -1,3 +1,3 @@
-@rem Used by the buildbot "test" step.
-cd PCbuild
-call rt.bat -d -q -x64 -uall -rwW %1 %2 %3 %4 %5 %6 %7 %8 %9
+@rem Used by the buildbot "test" step.\r
+cd PCbuild\r
+call rt.bat -d -q -x64 -uall -rwW %1 %2 %3 %4 %5 %6 %7 %8 %9\r
index a3a3579..e20cf54 100644 (file)
@@ -1,3 +1,3 @@
-@rem Used by the buildbot "test" step.
-cd PCbuild
-call rt.bat -d -q -uall -rwW %1 %2 %3 %4 %5 %6 %7 %8 %9
+@rem Used by the buildbot "test" step.\r
+cd PCbuild\r
+call rt.bat -d -q -uall -rwW %1 %2 %3 %4 %5 %6 %7 %8 %9\r
index 54af2fa..2fc19dc 100644 (file)
@@ -1,4 +1,4 @@
-_orig_open = open
+from __builtin__ import open as _orig_open
 
 class _BkFile:
     def __init__(self, file, mode, bufsize):
index 09105a2..af891fe 100644 (file)
@@ -132,34 +132,32 @@ docfile = 'python%s%s%s.chm' % (major, minor, docfile)
 
 # Build the mingw import library, libpythonXY.a
 # This requires 'nm' and 'dlltool' executables on your PATH
-def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):
+def build_mingw_lib(dll_path, def_file, dll_file, mingw_lib):
     warning = "WARNING: %s - libpythonXX.a not built"
-    nm = find_executable('nm')
+    gendef = find_executable('gendef')
     dlltool = find_executable('dlltool')
 
-    if not nm or not dlltool:
-        print warning % "nm and/or dlltool were not found"
+    if not gendef or not dlltool:
+        print warning % "gendef and/or dlltool were not found"
         return False
 
-    nm_command = '%s -Cs %s' % (nm, lib_file)
+    gendef_command = '%s - %s' % (gendef, dll_path)
     dlltool_command = "%s --dllname %s --def %s --output-lib %s" % \
         (dlltool, dll_file, def_file, mingw_lib)
-    export_match = re.compile(r"^_imp__(.*) in python\d+\.dll").match
+    if msilib.Win64:
+        dlltool_command += " -m i386:x86-64"
+    else:
+        dlltool_command += " -m i386"
 
     f = open(def_file,'w')
-    print >>f, "LIBRARY %s" % dll_file
-    print >>f, "EXPORTS"
-
-    nm_pipe = os.popen(nm_command)
-    for line in nm_pipe.readlines():
-        m = export_match(line)
-        if m:
-            print >>f, m.group(1)
+    gendef_pipe = os.popen(gendef_command)
+    for line in gendef_pipe.readlines():
+        print >>f, line
     f.close()
-    exit = nm_pipe.close()
+    exit = gendef_pipe.close()
 
     if exit:
-        print warning % "nm did not run successfully"
+        print warning % "gendef did not run successfully"
         return False
 
     if os.system(dlltool_command) != 0:
@@ -169,13 +167,11 @@ def build_mingw_lib(lib_file, def_file, dll_file, mingw_lib):
     return True
 
 # Target files (.def and .a) go in PCBuild directory
-lib_file = os.path.join(srcdir, PCBUILD, "python%s%s.lib" % (major, minor))
+dll_path = os.path.join(srcdir, PCBUILD, "python%s%s.dll" % (major, minor))
 def_file = os.path.join(srcdir, PCBUILD, "python%s%s.def" % (major, minor))
 dll_file = "python%s%s.dll" % (major, minor)
 mingw_lib = os.path.join(srcdir, PCBUILD, "libpython%s%s.a" % (major, minor))
 
-have_mingw = build_mingw_lib(lib_file, def_file, dll_file, mingw_lib)
-
 # Determine the target architecture
 if os.system("nmake /nologo /c /f msisupport.mak") != 0:
     raise RuntimeError("'nmake /f msisupport.mak' failed")
@@ -183,6 +179,7 @@ dll_path = os.path.join(srcdir, PCBUILD, dll_file)
 msilib.set_arch_from_file(dll_path)
 if msilib.pe_type(dll_path) != msilib.pe_type("msisupport.dll"):
     raise SystemError, "msisupport.dll for incorrect architecture"
+
 if msilib.Win64:
     upgrade_code = upgrade_code_64
     # Bump the last digit of the code by one, so that 32-bit and 64-bit
@@ -190,6 +187,8 @@ if msilib.Win64:
     digit = hex((int(product_code[-2],16)+1)%16)[-1]
     product_code = product_code[:-2] + digit + '}'
 
+have_mingw = build_mingw_lib(dll_path, def_file, dll_file, mingw_lib)
+
 if testpackage:
     ext = 'px'
     testprefix = 'x'
@@ -912,9 +911,9 @@ def generate_license():
                       ("Tk", "tk-8*", "license.terms"),
                       ("Tix", "tix-*", "license.terms")):
         out.write("\nThis copy of Python includes a copy of %s, which is licensed under the following terms:\n\n" % name)
-        dirs = glob.glob(srcdir+"/../"+pat)
+        dirs = glob.glob(srcdir+"/externals/"+pat)
         if not dirs:
-            raise ValueError, "Could not find "+srcdir+"/../"+pat
+            raise ValueError, "Could not find "+srcdir+"/externals/"+pat
         if len(dirs) > 2:
             raise ValueError, "Multiple copies of "+pat
         dir = dirs[0]
@@ -1019,6 +1018,8 @@ def add_files(db):
         # Add additional files
         dirs[dir]=lib
         lib.glob("*.txt")
+        lib.glob("*.whl")
+        lib.glob("*.0")
         if dir=='site-packages':
             lib.add_file("README.txt", src="README")
             continue
@@ -1043,6 +1044,7 @@ def add_files(db):
             lib.add_file("check_soundcard.vbs")
             lib.add_file("empty.vbs")
             lib.add_file("Sine-1000Hz-300ms.aif")
+            lib.add_file("revocation.crl")
             lib.glob("*.uue")
             lib.glob("*.pem")
             lib.glob("*.pck")
@@ -1117,7 +1119,7 @@ def add_files(db):
             lib.start_component("TkDLLs", tcltk)
             lib.add_file("_tkinter.pyd")
             dlls.append("_tkinter.pyd")
-            tcldir = os.path.normpath(srcdir+("/../tcltk%s/bin" % tclsuffix))
+            tcldir = os.path.normpath(srcdir+("/externals/tcltk%s/bin" % tclsuffix))
             for f in glob.glob1(tcldir, "*.dll"):
                 lib.add_file(f, src=os.path.join(tcldir, f))
     # check whether there are any unknown extensions
@@ -1141,7 +1143,7 @@ def add_files(db):
         lib.add_file('libpython%s%s.a' % (major, minor))
     if have_tcl:
         # Add Tcl/Tk
-        tcldirs = [(root, '../tcltk%s/lib' % tclsuffix, 'tcl')]
+        tcldirs = [(root, 'externals/tcltk%s/lib' % tclsuffix, 'tcl')]
         tcltk.set_current()
         while tcldirs:
             parent, phys, dir = tcldirs.pop()
index 2e4dc31..d8c426a 100644 (file)
@@ -66,4 +66,6 @@ product_codes = {
     '2.7.7121':'{5E0D187D-238B-4e96-9C75-C4CF141F5385}', # 2.7.7rc1
     '2.7.7150':'{049CA433-77A0-4e48-AC76-180A282C4E10}', # 2.7.7
     '2.7.8150':'{61121B12-88BD-4261-A6EE-AB32610A56DD}', # 2.7.8
+    '2.7.9121':'{AAB1E8FF-6D00-4409-8F13-BE365AB92FFE}', # 2.7.9rc1
+    '2.7.9150':'{79F081BF-7454-43DB-BD8F-9EE596813232}', # 2.7.9
 }
diff --git a/Tools/scripts/ftpmirror.py b/Tools/scripts/ftpmirror.py
deleted file mode 100755 (executable)
index 0f918b8..0000000
+++ /dev/null
@@ -1,400 +0,0 @@
-#! /usr/bin/env python
-
-"""Mirror a remote ftp subtree into a local directory tree.
-
-usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat]
-                 [-l username [-p passwd [-a account]]]
-                 hostname[:port] [remotedir [localdir]]
--v: verbose
--q: quiet
--i: interactive mode
--m: macintosh server (NCSA telnet 2.4) (implies -n -s '*.o')
--n: don't log in
--r: remove local files/directories no longer pertinent
--l username [-p passwd [-a account]]: login info (default .netrc or anonymous)
--s pat: skip files matching pattern
-hostname: remote host w/ optional port separated by ':'
-remotedir: remote directory (default initial)
-localdir: local directory (default current)
-"""
-
-import os
-import sys
-import time
-import getopt
-import ftplib
-import netrc
-from fnmatch import fnmatch
-
-# Print usage message and exit
-def usage(*args):
-    sys.stdout = sys.stderr
-    for msg in args: print msg
-    print __doc__
-    sys.exit(2)
-
-verbose = 1 # 0 for -q, 2 for -v
-interactive = 0
-mac = 0
-rmok = 0
-nologin = 0
-skippats = ['.', '..', '.mirrorinfo']
-
-# Main program: parse command line and start processing
-def main():
-    global verbose, interactive, mac, rmok, nologin
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v')
-    except getopt.error, msg:
-        usage(msg)
-    login = ''
-    passwd = ''
-    account = ''
-    if not args: usage('hostname missing')
-    host = args[0]
-    port = 0
-    if ':' in host:
-        host, port = host.split(':', 1)
-        port = int(port)
-    try:
-        auth = netrc.netrc().authenticators(host)
-        if auth is not None:
-            login, account, passwd = auth
-    except (netrc.NetrcParseError, IOError):
-        pass
-    for o, a in opts:
-        if o == '-l': login = a
-        if o == '-p': passwd = a
-        if o == '-a': account = a
-        if o == '-v': verbose = verbose + 1
-        if o == '-q': verbose = 0
-        if o == '-i': interactive = 1
-        if o == '-m': mac = 1; nologin = 1; skippats.append('*.o')
-        if o == '-n': nologin = 1
-        if o == '-r': rmok = 1
-        if o == '-s': skippats.append(a)
-    remotedir = ''
-    localdir = ''
-    if args[1:]:
-        remotedir = args[1]
-        if args[2:]:
-            localdir = args[2]
-            if args[3:]: usage('too many arguments')
-    #
-    f = ftplib.FTP()
-    if verbose: print "Connecting to '%s%s'..." % (host,
-                                                   (port and ":%d"%port or ""))
-    f.connect(host,port)
-    if not nologin:
-        if verbose:
-            print 'Logging in as %r...' % (login or 'anonymous')
-        f.login(login, passwd, account)
-    if verbose: print 'OK.'
-    pwd = f.pwd()
-    if verbose > 1: print 'PWD =', repr(pwd)
-    if remotedir:
-        if verbose > 1: print 'cwd(%s)' % repr(remotedir)
-        f.cwd(remotedir)
-        if verbose > 1: print 'OK.'
-        pwd = f.pwd()
-        if verbose > 1: print 'PWD =', repr(pwd)
-    #
-    mirrorsubdir(f, localdir)
-
-# Core logic: mirror one subdirectory (recursively)
-def mirrorsubdir(f, localdir):
-    pwd = f.pwd()
-    if localdir and not os.path.isdir(localdir):
-        if verbose: print 'Creating local directory', repr(localdir)
-        try:
-            makedir(localdir)
-        except os.error, msg:
-            print "Failed to establish local directory", repr(localdir)
-            return
-    infofilename = os.path.join(localdir, '.mirrorinfo')
-    try:
-        text = open(infofilename, 'r').read()
-    except IOError, msg:
-        text = '{}'
-    try:
-        info = eval(text)
-    except (SyntaxError, NameError):
-        print 'Bad mirror info in', repr(infofilename)
-        info = {}
-    subdirs = []
-    listing = []
-    if verbose: print 'Listing remote directory %r...' % (pwd,)
-    f.retrlines('LIST', listing.append)
-    filesfound = []
-    for line in listing:
-        if verbose > 1: print '-->', repr(line)
-        if mac:
-            # Mac listing has just filenames;
-            # trailing / means subdirectory
-            filename = line.strip()
-            mode = '-'
-            if filename[-1:] == '/':
-                filename = filename[:-1]
-                mode = 'd'
-            infostuff = ''
-        else:
-            # Parse, assuming a UNIX listing
-            words = line.split(None, 8)
-            if len(words) < 6:
-                if verbose > 1: print 'Skipping short line'
-                continue
-            filename = words[-1].lstrip()
-            i = filename.find(" -> ")
-            if i >= 0:
-                # words[0] had better start with 'l'...
-                if verbose > 1:
-                    print 'Found symbolic link %r' % (filename,)
-                linkto = filename[i+4:]
-                filename = filename[:i]
-            infostuff = words[-5:-1]
-            mode = words[0]
-        skip = 0
-        for pat in skippats:
-            if fnmatch(filename, pat):
-                if verbose > 1:
-                    print 'Skip pattern', repr(pat),
-                    print 'matches', repr(filename)
-                skip = 1
-                break
-        if skip:
-            continue
-        if mode[0] == 'd':
-            if verbose > 1:
-                print 'Remembering subdirectory', repr(filename)
-            subdirs.append(filename)
-            continue
-        filesfound.append(filename)
-        if info.has_key(filename) and info[filename] == infostuff:
-            if verbose > 1:
-                print 'Already have this version of',repr(filename)
-            continue
-        fullname = os.path.join(localdir, filename)
-        tempname = os.path.join(localdir, '@'+filename)
-        if interactive:
-            doit = askabout('file', filename, pwd)
-            if not doit:
-                if not info.has_key(filename):
-                    info[filename] = 'Not retrieved'
-                continue
-        try:
-            os.unlink(tempname)
-        except os.error:
-            pass
-        if mode[0] == 'l':
-            if verbose:
-                print "Creating symlink %r -> %r" % (filename, linkto)
-            try:
-                os.symlink(linkto, tempname)
-            except IOError, msg:
-                print "Can't create %r: %s" % (tempname, msg)
-                continue
-        else:
-            try:
-                fp = open(tempname, 'wb')
-            except IOError, msg:
-                print "Can't create %r: %s" % (tempname, msg)
-                continue
-            if verbose:
-                print 'Retrieving %r from %r as %r...' % (filename, pwd, fullname)
-            if verbose:
-                fp1 = LoggingFile(fp, 1024, sys.stdout)
-            else:
-                fp1 = fp
-            t0 = time.time()
-            try:
-                f.retrbinary('RETR ' + filename,
-                             fp1.write, 8*1024)
-            except ftplib.error_perm, msg:
-                print msg
-            t1 = time.time()
-            bytes = fp.tell()
-            fp.close()
-            if fp1 != fp:
-                fp1.close()
-        try:
-            os.unlink(fullname)
-        except os.error:
-            pass            # Ignore the error
-        try:
-            os.rename(tempname, fullname)
-        except os.error, msg:
-            print "Can't rename %r to %r: %s" % (tempname, fullname, msg)
-            continue
-        info[filename] = infostuff
-        writedict(info, infofilename)
-        if verbose and mode[0] != 'l':
-            dt = t1 - t0
-            kbytes = bytes / 1024.0
-            print int(round(kbytes)),
-            print 'Kbytes in',
-            print int(round(dt)),
-            print 'seconds',
-            if t1 > t0:
-                print '(~%d Kbytes/sec)' % \
-                          int(round(kbytes/dt),)
-            print
-    #
-    # Remove files from info that are no longer remote
-    deletions = 0
-    for filename in info.keys():
-        if filename not in filesfound:
-            if verbose:
-                print "Removing obsolete info entry for",
-                print repr(filename), "in", repr(localdir or ".")
-            del info[filename]
-            deletions = deletions + 1
-    if deletions:
-        writedict(info, infofilename)
-    #
-    # Remove local files that are no longer in the remote directory
-    try:
-        if not localdir: names = os.listdir(os.curdir)
-        else: names = os.listdir(localdir)
-    except os.error:
-        names = []
-    for name in names:
-        if name[0] == '.' or info.has_key(name) or name in subdirs:
-            continue
-        skip = 0
-        for pat in skippats:
-            if fnmatch(name, pat):
-                if verbose > 1:
-                    print 'Skip pattern', repr(pat),
-                    print 'matches', repr(name)
-                skip = 1
-                break
-        if skip:
-            continue
-        fullname = os.path.join(localdir, name)
-        if not rmok:
-            if verbose:
-                print 'Local file', repr(fullname),
-                print 'is no longer pertinent'
-            continue
-        if verbose: print 'Removing local file/dir', repr(fullname)
-        remove(fullname)
-    #
-    # Recursively mirror subdirectories
-    for subdir in subdirs:
-        if interactive:
-            doit = askabout('subdirectory', subdir, pwd)
-            if not doit: continue
-        if verbose: print 'Processing subdirectory', repr(subdir)
-        localsubdir = os.path.join(localdir, subdir)
-        pwd = f.pwd()
-        if verbose > 1:
-            print 'Remote directory now:', repr(pwd)
-            print 'Remote cwd', repr(subdir)
-        try:
-            f.cwd(subdir)
-        except ftplib.error_perm, msg:
-            print "Can't chdir to", repr(subdir), ":", repr(msg)
-        else:
-            if verbose: print 'Mirroring as', repr(localsubdir)
-            mirrorsubdir(f, localsubdir)
-            if verbose > 1: print 'Remote cwd ..'
-            f.cwd('..')
-        newpwd = f.pwd()
-        if newpwd != pwd:
-            print 'Ended up in wrong directory after cd + cd ..'
-            print 'Giving up now.'
-            break
-        else:
-            if verbose > 1: print 'OK.'
-
-# Helper to remove a file or directory tree
-def remove(fullname):
-    if os.path.isdir(fullname) and not os.path.islink(fullname):
-        try:
-            names = os.listdir(fullname)
-        except os.error:
-            names = []
-        ok = 1
-        for name in names:
-            if not remove(os.path.join(fullname, name)):
-                ok = 0
-        if not ok:
-            return 0
-        try:
-            os.rmdir(fullname)
-        except os.error, msg:
-            print "Can't remove local directory %r: %s" % (fullname, msg)
-            return 0
-    else:
-        try:
-            os.unlink(fullname)
-        except os.error, msg:
-            print "Can't remove local file %r: %s" % (fullname, msg)
-            return 0
-    return 1
-
-# Wrapper around a file for writing to write a hash sign every block.
-class LoggingFile:
-    def __init__(self, fp, blocksize, outfp):
-        self.fp = fp
-        self.bytes = 0
-        self.hashes = 0
-        self.blocksize = blocksize
-        self.outfp = outfp
-    def write(self, data):
-        self.bytes = self.bytes + len(data)
-        hashes = int(self.bytes) / self.blocksize
-        while hashes > self.hashes:
-            self.outfp.write('#')
-            self.outfp.flush()
-            self.hashes = self.hashes + 1
-        self.fp.write(data)
-    def close(self):
-        self.outfp.write('\n')
-
-# Ask permission to download a file.
-def askabout(filetype, filename, pwd):
-    prompt = 'Retrieve %s %s from %s ? [ny] ' % (filetype, filename, pwd)
-    while 1:
-        reply = raw_input(prompt).strip().lower()
-        if reply in ['y', 'ye', 'yes']:
-            return 1
-        if reply in ['', 'n', 'no', 'nop', 'nope']:
-            return 0
-        print 'Please answer yes or no.'
-
-# Create a directory if it doesn't exist.  Recursively create the
-# parent directory as well if needed.
-def makedir(pathname):
-    if os.path.isdir(pathname):
-        return
-    dirname = os.path.dirname(pathname)
-    if dirname: makedir(dirname)
-    os.mkdir(pathname, 0777)
-
-# Write a dictionary to a file in a way that can be read back using
-# rval() but is still somewhat readable (i.e. not a single long line).
-# Also creates a backup file.
-def writedict(dict, filename):
-    dir, fname = os.path.split(filename)
-    tempname = os.path.join(dir, '@' + fname)
-    backup = os.path.join(dir, fname + '~')
-    try:
-        os.unlink(backup)
-    except os.error:
-        pass
-    fp = open(tempname, 'w')
-    fp.write('{\n')
-    for key, value in dict.items():
-        fp.write('%r: %r,\n' % (key, value))
-    fp.write('}\n')
-    fp.close()
-    try:
-        os.rename(filename, backup)
-    except os.error:
-        pass
-    os.rename(tempname, filename)
-
-
-if __name__ == '__main__':
-    main()
index c64501e..40b1bce 100755 (executable)
@@ -29,7 +29,7 @@ p_macro = re.compile(
   '^[\t ]*#[\t ]*define[\t ]+'
   '([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+')
 
-p_include = re.compile('^[\t ]*#[\t ]*include[\t ]+<([a-zA-Z0-9_/\.]+)')
+p_include = re.compile('^[\t ]*#[\t ]*include[\t ]+<([^>\n]+)>')
 
 p_comment = re.compile(r'/\*([^*]+|\*+[^/])*(\*+/)?')
 p_cpp_comment = re.compile('//.*')
index 10244d1..3fb4985 100755 (executable)
@@ -5,8 +5,7 @@ This script should be called *manually* when we want to upgrade SSLError
 `library` and `reason` mnemnonics to a more recent OpenSSL version.
 
 It takes two arguments:
-- the path to the OpenSSL include files' directory
-  (e.g. openssl-1.0.1-beta3/include/openssl/)
+- the path to the OpenSSL source tree (e.g. git checkout)
 - the path to the C file to be generated
   (probably Modules/_ssl_data.h)
 """
@@ -15,9 +14,10 @@ import datetime
 import os
 import re
 import sys
+import _ssl
 
 
-def parse_error_codes(h_file, prefix):
+def parse_error_codes(h_file, prefix, libcode):
     pat = re.compile(r"#define\W+(%s([\w]+))\W+(\d+)\b" % re.escape(prefix))
     codes = []
     with open(h_file, "r", encoding="latin1") as f:
@@ -26,7 +26,8 @@ def parse_error_codes(h_file, prefix):
             if match:
                 code, name, num = match.groups()
                 num = int(num)
-                codes.append((code, name, num))
+                # e.g. ("SSL_R_BAD_DATA", ("ERR_LIB_SSL", "BAD_DATA", 390))
+                codes.append((code, (libcode, name, num)))
     return codes
 
 if __name__ == "__main__":
@@ -34,12 +35,32 @@ if __name__ == "__main__":
     outfile = sys.argv[2]
     use_stdout = outfile == '-'
     f = sys.stdout if use_stdout else open(outfile, "w")
-    error_libraries = (
-        # (library code, mnemonic, error prefix, header file)
-        ('ERR_LIB_PEM', 'PEM', 'PEM_R_', 'pem.h'),
-        ('ERR_LIB_SSL', 'SSL', 'SSL_R_', 'ssl.h'),
-        ('ERR_LIB_X509', 'X509', 'X509_R_', 'x509.h'),
-        )
+    error_libraries = {
+        # mnemonic -> (library code, error prefix, header file)
+        'PEM': ('ERR_LIB_PEM', 'PEM_R_', 'crypto/pem/pem.h'),
+        'SSL': ('ERR_LIB_SSL', 'SSL_R_', 'ssl/ssl.h'),
+        'X509': ('ERR_LIB_X509', 'X509_R_', 'crypto/x509/x509.h'),
+        }
+
+    # Read codes from libraries
+    new_codes = []
+    for libcode, prefix, h_file in sorted(error_libraries.values()):
+        new_codes += parse_error_codes(os.path.join(openssl_inc, h_file),
+                                       prefix, libcode)
+    new_code_nums = set((libcode, num)
+                        for (code, (libcode, name, num)) in new_codes)
+
+    # Merge with existing codes (in case some old codes disappeared).
+    codes = {}
+    for errname, (libnum, errnum) in _ssl.err_names_to_codes.items():
+        lib = error_libraries[_ssl.lib_codes_to_names[libnum]]
+        libcode = lib[0]              # e.g. ERR_LIB_PEM
+        errcode = lib[1] + errname    # e.g. SSL_R_BAD_SSL_SESSION_ID_LENGTH
+        # Only keep it if the numeric codes weren't reused
+        if (libcode, errnum) not in new_code_nums:
+            codes[errcode] = libcode, errname, errnum
+    codes.update(dict(new_codes))
+
     def w(l):
         f.write(l + "\n")
     w("/* File generated by Tools/ssl/make_ssl_data.py */")
@@ -47,21 +68,19 @@ if __name__ == "__main__":
     w("")
 
     w("static struct py_ssl_library_code library_codes[] = {")
-    for libcode, mnemo, _, _ in error_libraries:
+    for mnemo, (libcode, _, _) in sorted(error_libraries.items()):
         w('    {"%s", %s},' % (mnemo, libcode))
     w('    { NULL }')
     w('};')
     w("")
 
     w("static struct py_ssl_error_code error_codes[] = {")
-    for libcode, _, prefix, h_file in error_libraries:
-        codes = parse_error_codes(os.path.join(openssl_inc, h_file), prefix)
-        for code, name, num in sorted(codes):
-            w('  #ifdef %s' % (code))
-            w('    {"%s", %s, %s},' % (name, libcode, code))
-            w('  #else')
-            w('    {"%s", %s, %d},' % (name, libcode, num))
-            w('  #endif')
+    for errcode, (libcode, name, num) in sorted(codes.items()):
+        w('  #ifdef %s' % (errcode))
+        w('    {"%s", %s, %s},' % (name, libcode, errcode))
+        w('  #else')
+        w('    {"%s", %s, %d},' % (name, libcode, num))
+        w('  #endif')
     w('    { NULL }')
     w('};')
     if not use_stdout:
index 2228d89..6a6a671 100644 (file)
@@ -1,7 +1,7 @@
-@rem Recreate some python charmap codecs from the Windows function
-@rem MultiByteToWideChar.
-
-@cd /d %~dp0
-@mkdir build
-@rem Arabic DOS code page
-c:\python26\python genwincodec.py 720 > build/cp720.py
+@rem Recreate some python charmap codecs from the Windows function\r
+@rem MultiByteToWideChar.\r
+\r
+@cd /d %~dp0\r
+@mkdir build\r
+@rem Arabic DOS code page\r
+c:\python26\python genwincodec.py 720 > build/cp720.py\r
diff --git a/aclocal.m4 b/aclocal.m4
new file mode 100644 (file)
index 0000000..7d25fb9
--- /dev/null
@@ -0,0 +1,229 @@
+# generated automatically by aclocal 1.14.1 -*- Autoconf -*-
+
+# Copyright (C) 1996-2013 Free Software Foundation, Inc.
+
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])])
+# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
+# serial 1 (pkg-config-0.24)
+# 
+# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# PKG_PROG_PKG_CONFIG([MIN-VERSION])
+# ----------------------------------
+AC_DEFUN([PKG_PROG_PKG_CONFIG],
+[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
+m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
+m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
+AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
+AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
+AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
+
+if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
+       AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+fi
+if test -n "$PKG_CONFIG"; then
+       _pkg_min_version=m4_default([$1], [0.9.0])
+       AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
+       if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+               AC_MSG_RESULT([yes])
+       else
+               AC_MSG_RESULT([no])
+               PKG_CONFIG=""
+       fi
+fi[]dnl
+])# PKG_PROG_PKG_CONFIG
+
+# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#
+# Check to see whether a particular set of modules exists.  Similar
+# to PKG_CHECK_MODULES(), but does not set variables or print errors.
+#
+# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+# only at the first occurence in configure.ac, so if the first place
+# it's called might be skipped (such as if it is within an "if", you
+# have to call PKG_CHECK_EXISTS manually
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_EXISTS],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+if test -n "$PKG_CONFIG" && \
+    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
+  m4_default([$2], [:])
+m4_ifvaln([$3], [else
+  $3])dnl
+fi])
+
+# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+# ---------------------------------------------
+m4_define([_PKG_CONFIG],
+[if test -n "$$1"; then
+    pkg_cv_[]$1="$$1"
+ elif test -n "$PKG_CONFIG"; then
+    PKG_CHECK_EXISTS([$3],
+                     [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
+                     test "x$?" != "x0" && pkg_failed=yes ],
+                    [pkg_failed=yes])
+ else
+    pkg_failed=untried
+fi[]dnl
+])# _PKG_CONFIG
+
+# _PKG_SHORT_ERRORS_SUPPORTED
+# -----------------------------
+AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=yes
+else
+        _pkg_short_errors_supported=no
+fi[]dnl
+])# _PKG_SHORT_ERRORS_SUPPORTED
+
+
+# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+# [ACTION-IF-NOT-FOUND])
+#
+#
+# Note that if there is a possibility the first call to
+# PKG_CHECK_MODULES might not happen, you should be sure to include an
+# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
+#
+#
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_MODULES],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
+AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
+
+pkg_failed=no
+AC_MSG_CHECKING([for $1])
+
+_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
+_PKG_CONFIG([$1][_LIBS], [libs], [$2])
+
+m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
+and $1[]_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details.])
+
+if test $pkg_failed = yes; then
+       AC_MSG_RESULT([no])
+        _PKG_SHORT_ERRORS_SUPPORTED
+        if test $_pkg_short_errors_supported = yes; then
+               $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
+        else 
+               $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
+        fi
+       # Put the nasty error message in config.log where it belongs
+       echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
+
+       m4_default([$4], [AC_MSG_ERROR(
+[Package requirements ($2) were not met:
+
+$$1_PKG_ERRORS
+
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
+
+_PKG_TEXT])[]dnl
+        ])
+elif test $pkg_failed = untried; then
+       AC_MSG_RESULT([no])
+       m4_default([$4], [AC_MSG_FAILURE(
+[The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
+
+_PKG_TEXT
+
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
+        ])
+else
+       $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
+       $1[]_LIBS=$pkg_cv_[]$1[]_LIBS
+        AC_MSG_RESULT([yes])
+       $3
+fi[]dnl
+])# PKG_CHECK_MODULES
+
+
+# PKG_INSTALLDIR(DIRECTORY)
+# -------------------------
+# Substitutes the variable pkgconfigdir as the location where a module
+# should install pkg-config .pc files. By default the directory is
+# $libdir/pkgconfig, but the default can be changed by passing
+# DIRECTORY. The user can override through the --with-pkgconfigdir
+# parameter.
+AC_DEFUN([PKG_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([pkgconfigdir],
+    [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
+    [with_pkgconfigdir=]pkg_default)
+AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+]) dnl PKG_INSTALLDIR
+
+
+# PKG_NOARCH_INSTALLDIR(DIRECTORY)
+# -------------------------
+# Substitutes the variable noarch_pkgconfigdir as the location where a
+# module should install arch-independent pkg-config .pc files. By
+# default the directory is $datadir/pkgconfig, but the default can be
+# changed by passing DIRECTORY. The user can override through the
+# --with-noarch-pkgconfigdir parameter.
+AC_DEFUN([PKG_NOARCH_INSTALLDIR],
+[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
+m4_pushdef([pkg_description],
+    [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
+AC_ARG_WITH([noarch-pkgconfigdir],
+    [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
+    [with_noarch_pkgconfigdir=]pkg_default)
+AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
+m4_popdef([pkg_default])
+m4_popdef([pkg_description])
+]) dnl PKG_NOARCH_INSTALLDIR
+
+
+# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
+# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+# -------------------------------------------
+# Retrieves the value of the pkg-config variable for the given module.
+AC_DEFUN([PKG_CHECK_VAR],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
+
+_PKG_CONFIG([$1], [variable="][$3]["], [$2])
+AS_VAR_COPY([$1], [pkg_cv_][$1])
+
+AS_VAR_IF([$1], [""], [$5], [$4])dnl
+])# PKG_CHECK_VAR
+
index 68033f5..8cf777e 100755 (executable)
--- a/configure
+++ b/configure
@@ -648,6 +648,8 @@ USE_SIGNAL_MODULE
 TCLTK_LIBS
 TCLTK_INCLUDES
 LIBFFI_INCLUDEDIR
+PKG_CONFIG_LIBDIR
+PKG_CONFIG_PATH
 PKG_CONFIG
 SHLIBS
 CFLAGSFORSHARED
@@ -705,6 +707,7 @@ EXPORT_MACOSX_DEPLOYMENT_TARGET
 CONFIGURE_MACOSX_DEPLOYMENT_TARGET
 EXTRAMACHDEPPATH
 EXTRAPLATDIR
+PLATDIR
 SGI_ABI
 _PYTHON_HOST_PLATFORM
 MACHDEP
@@ -818,7 +821,10 @@ CFLAGS
 LDFLAGS
 LIBS
 CPPFLAGS
-CPP'
+CPP
+PKG_CONFIG
+PKG_CONFIG_PATH
+PKG_CONFIG_LIBDIR'
 
 
 # Initialize some variables set by options.
@@ -1501,6 +1507,11 @@ Some influential environment variables:
   CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
               you have headers in a nonstandard directory <include dir>
   CPP         C preprocessor
+  PKG_CONFIG  path to pkg-config utility
+  PKG_CONFIG_PATH
+              directories to add to pkg-config's search path
+  PKG_CONFIG_LIBDIR
+              path overriding pkg-config's built-in search path
 
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
@@ -2881,7 +2892,7 @@ $as_echo_n "checking for python interpreter for cross build... " >&6; }
        fi
         { $as_echo "$as_me:${as_lineno-$LINENO}: result: $interp" >&5
 $as_echo "$interp" >&6; }
-       PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/plat-$(MACHDEP) '$interp
+       PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR) '$interp
     fi
 elif test "$cross_compiling" = maybe; then
     as_fn_error $? "Cross compiling required --host=HOST-TUPLE and --build=ARCH" "$LINENO" 5
@@ -3370,6 +3381,9 @@ fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MACHDEP" >&5
 $as_echo "$MACHDEP" >&6; }
 
+
+PLATDIR=plat-$MACHDEP
+
 # And add extra plat-mac for darwin
 
 
@@ -8541,6 +8555,48 @@ _ACEOF
 
 fi
        # Dynamic linking for HP-UX
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for RAND_egd in -lcrypto" >&5
+$as_echo_n "checking for RAND_egd in -lcrypto... " >&6; }
+if ${ac_cv_lib_crypto_RAND_egd+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lcrypto  $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 RAND_egd ();
+int
+main ()
+{
+return RAND_egd ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_crypto_RAND_egd=yes
+else
+  ac_cv_lib_crypto_RAND_egd=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_crypto_RAND_egd" >&5
+$as_echo "$ac_cv_lib_crypto_RAND_egd" >&6; }
+if test "x$ac_cv_lib_crypto_RAND_egd" = xyes; then :
+
+$as_echo "#define HAVE_RAND_EGD 1" >>confdefs.h
+
+fi
+
 
 # only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
@@ -8828,7 +8884,15 @@ $as_echo "no" >&6; }
 fi
 
 
-if test -n "$ac_tool_prefix"; then
+
+
+
+
+
+
+
+if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
+       if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args.
 set dummy ${ac_tool_prefix}pkg-config; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
@@ -8926,6 +8990,20 @@ else
   PKG_CONFIG="$ac_cv_path_PKG_CONFIG"
 fi
 
+fi
+if test -n "$PKG_CONFIG"; then
+       _pkg_min_version=0.9.0
+       { $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5
+$as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; }
+       if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+               { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+       else
+               { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+               PKG_CONFIG=""
+       fi
+fi
 
 # Check for use of the system expat library
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-system-expat" >&5
@@ -10165,6 +10243,7 @@ $as_echo "MACHDEP_OBJS" >&6; }
 for ac_func in alarm setitimer getitimer bind_textdomain_codeset chown \
  clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \
  gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \
+ getentropy \
  getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \
  initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime mmap \
  mremap nice pathconf pause plock poll pthread_init \
index 94a215e..78fe3c7 100644 (file)
@@ -33,7 +33,7 @@ if test "$cross_compiling" = yes; then
            AC_MSG_ERROR([python$PACKAGE_VERSION interpreter not found])
        fi
         AC_MSG_RESULT($interp)
-       PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/plat-$(MACHDEP) '$interp
+       PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR) '$interp
     fi
 elif test "$cross_compiling" = maybe; then
     AC_MSG_ERROR([Cross compiling required --host=HOST-TUPLE and --build=ARCH])
@@ -493,6 +493,9 @@ then
 fi
 AC_MSG_RESULT($MACHDEP)
 
+AC_SUBST(PLATDIR)
+PLATDIR=plat-$MACHDEP
+
 # And add extra plat-mac for darwin
 AC_SUBST(EXTRAPLATDIR)
 AC_SUBST(EXTRAMACHDEPPATH)
@@ -2221,6 +2224,9 @@ AC_MSG_RESULT($SHLIBS)
 # checks for libraries
 AC_CHECK_LIB(dl, dlopen)       # Dynamic linking for SunOS/Solaris and SYSV
 AC_CHECK_LIB(dld, shl_load)    # Dynamic linking for HP-UX
+AC_CHECK_LIB(crypto, RAND_egd,
+             AC_DEFINE(HAVE_RAND_EGD, 1,
+             [Define if the libcrypto has RAND_egd]))
 
 # only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
@@ -2271,7 +2277,7 @@ LIBS="$withval $LIBS"
 ],
 [AC_MSG_RESULT(no)])
 
-AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+PKG_PROG_PKG_CONFIG
 
 # Check for use of the system expat library
 AC_MSG_CHECKING(for --with-system-expat)
@@ -2913,6 +2919,7 @@ AC_MSG_RESULT(MACHDEP_OBJS)
 AC_CHECK_FUNCS(alarm setitimer getitimer bind_textdomain_codeset chown \
  clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \
  gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \
+ getentropy \
  getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \
  initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime mmap \
  mremap nice pathconf pause plock poll pthread_init \
index d6d479a..8e810da 100644 (file)
 /* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */
 #undef HAVE_GETC_UNLOCKED
 
+/* Define to 1 if you have the `getentropy' function. */
+#undef HAVE_GETENTROPY
+
 /* Define to 1 if you have the `getgroups' function. */
 #undef HAVE_GETGROUPS
 
 /* Define to 1 if you have the `putenv' function. */
 #undef HAVE_PUTENV
 
+/* Define if the libcrypto has RAND_egd */
+#undef HAVE_RAND_EGD
+
 /* Define to 1 if you have the `readlink' function. */
 #undef HAVE_READLINK
 
index 7868b7b..6a6ad23 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -696,7 +696,7 @@ class PyBuildExt(build_ext):
         exts.append( Extension('audioop', ['audioop.c']) )
 
         # Disabled on 64-bit platforms
-        if sys.maxint != 9223372036854775807L:
+        if sys.maxsize != 9223372036854775807L:
             # Operations on images
             exts.append( Extension('imageop', ['imageop.c']) )
         else: