Merge.
diff --git a/.bzrignore b/.bzrignore
index e588595..2527052 100644
--- a/.bzrignore
+++ b/.bzrignore
@@ -13,6 +13,7 @@
platform
pyconfig.h
libpython*.a
+libpython*.so*
python.exe
python-gdb.py
reflog.txt
@@ -33,3 +34,6 @@
Lib/test/data/*
Lib/lib2to3/Grammar*.pickle
Lib/lib2to3/PatternGrammar*.pickle
+.coverage
+coverage/*
+htmlcov/*
diff --git a/.hgeol b/.hgeol
index e1c1992..fe66605 100644
--- a/.hgeol
+++ b/.hgeol
@@ -27,8 +27,9 @@
**.zip = BIN
Lib/email/test/data/msg_26.txt = BIN
-Lib/test/sndhdrdata/sndhdr.* = BIN
+Lib/test/cjkencodings/* = BIN
Lib/test/decimaltestdata/*.decTest = BIN
+Lib/test/sndhdrdata/sndhdr.* = BIN
# All other files (which presumably are human-editable) are "native".
# This must be the last rule!
diff --git a/.hgignore b/.hgignore
index f2fb2d6..8c402ff 100644
--- a/.hgignore
+++ b/.hgignore
@@ -38,14 +38,13 @@
syntax: glob
python.exe-gdb.py
libpython*.a
+libpython*.so*
*.swp
*.o
*.pyc
*.pyo
*.pyd
*.cover
-*.orig
-*.rej
*~
Lib/lib2to3/*.pickle
Lib/test/data/*
@@ -62,3 +61,6 @@
PCbuild/*.ncb
PCbuild/*.bsc
PCbuild/Win32-temp-*
+.coverage
+coverage/
+htmlcov/
diff --git a/.hgtags b/.hgtags
index 91ded74..2e59791 100644
--- a/.hgtags
+++ b/.hgtags
@@ -112,6 +112,8 @@
657f16582943739b906f66f7efad4014492c8b1c v2.5.5c1
1dc91e9dd5c13a4bc2d3bb7d4b5896ab264f2325 v2.5.5c2
7098a46f0b75e5aacfaf81d65d72e3613b023532 v2.5.5
+a87c7b96672b69dffef64c59b56fba5bb2059b99 v2.5.6c1
+de34c7b097e8d66b1140c211dbd61d48b31ba483 v2.5.6
2d0bd095c420b0711000d9be66848f6cfd972b3b v2.6a1
eec144917a189be11ed5efa35c6604d03bc62bcc v2.6a2
48e9fb0a721799877f26edaef01ac6e6029b6812 v2.6a3
@@ -146,3 +148,5 @@
2145593d108de62ebf770987a4ac2a57d268c9d1 v2.7
63d9f00fea0730c1c437a50f64a42b7792bdcbfb v2.7.1rc1
5395f96588d4f0199d329cb79eb109648dc4ef5e v2.7.1
+f48756685406e8d0fa9d23d841fceb07e36a5656 v2.7.2rc1
+8527427914a29d895bcb30be76a465143993a793 v2.7.2
diff --git a/Demo/turtle/about_turtle.txt b/Demo/turtle/about_turtle.txt
index a42800b..4d290be 100644
--- a/Demo/turtle/about_turtle.txt
+++ b/Demo/turtle/about_turtle.txt
@@ -7,10 +7,10 @@
kids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.
-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
+Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
the direction it is facing, drawing a line as it moves. Give it the
-command turtle.left(25), and it rotates in-place 25 degrees clockwise.
+command turtle.right(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.
diff --git a/Doc/ACKS.txt b/Doc/ACKS.txt
index 2aa0316..ec9efb0 100644
--- a/Doc/ACKS.txt
+++ b/Doc/ACKS.txt
@@ -77,6 +77,7 @@
* Travis B. Hartwell
* Tim Hatch
* Janko Hauser
+ * Ben Hayden
* Thomas Heller
* Bernhard Herzog
* Magnus L. Hetland
@@ -103,6 +104,7 @@
* Robert Kern
* Jim Kerr
* Jan Kim
+ * Kamil Kisiel
* Greg Kochanski
* Guido Kollerie
* Peter A. Koren
@@ -139,7 +141,8 @@
* Ross Moore
* Sjoerd Mullender
* Dale Nagata
- * Michal Nowikowski
+ * Michal Nowikowski
+ * Steffen Daode Nurpmeso
* Ng Pheng Siong
* Koray Oner
* Tomas Oppelstrup
@@ -180,6 +183,7 @@
* Joakim Sernbrant
* Justin Sheehy
* Charlie Shepherd
+ * Yue Shuaijie
* Michael Simcich
* Ionel Simionescu
* Michael Sloan
@@ -197,6 +201,7 @@
* Kalle Svensson
* Jim Tittsler
* David Turner
+ * Sandro Tosi
* Ville Vainio
* Martijn Vries
* Charles G. Waldman
@@ -214,6 +219,7 @@
* Collin Winter
* Blake Winton
* Dan Wolfe
+ * Adam Woodbeck
* Steven Work
* Thomas Wouters
* Ka-Ping Yee
diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst
index a75b07b..21e8c4a 100644
--- a/Doc/c-api/buffer.rst
+++ b/Doc/c-api/buffer.rst
@@ -276,7 +276,7 @@
.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
Fill the *strides* array with byte-strides of a contiguous (C-style if
- *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'`` array of the
+ *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'``) array of the
given shape with the given number of bytes per element.
diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst
index 8b1e8fc..a001145 100644
--- a/Doc/c-api/exceptions.rst
+++ b/Doc/c-api/exceptions.rst
@@ -352,10 +352,10 @@
.. cfunction:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict)
- This utility function creates and returns a new exception object. The *name*
+ This utility function creates and returns a new exception class. The *name*
argument must be the name of the new exception, a C string of the form
- ``module.class``. The *base* and *dict* arguments are normally *NULL*. This
- creates a class object derived from :exc:`Exception` (accessible in C as
+ ``module.classname``. The *base* and *dict* arguments are normally *NULL*.
+ This creates a class object derived from :exc:`Exception` (accessible in C as
:cdata:`PyExc_Exception`).
The :attr:`__module__` attribute of the new class is set to the first part (up
diff --git a/Doc/c-api/file.rst b/Doc/c-api/file.rst
index bdb8c49..93f6b64 100644
--- a/Doc/c-api/file.rst
+++ b/Doc/c-api/file.rst
@@ -55,7 +55,8 @@
Create a new :ctype:`PyFileObject` from the already-open standard C file
pointer, *fp*. The function *close* will be called when the file should be
- closed. Return *NULL* on failure.
+ closed. Return *NULL* and close the file using *close* on failure.
+ *close* is optional and can be set to *NULL*.
.. cfunction:: FILE* PyFile_AsFile(PyObject \*p)
diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
index 27408a4..c323eef 100644
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -126,7 +126,7 @@
program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
returned string points into static storage; the caller should not modify its
value. This corresponds to the :makevar:`prefix` variable in the top-level
- :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
+ :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
script at build time. The value is available to Python code as ``sys.prefix``.
It is only useful on Unix. See also the next function.
@@ -139,7 +139,7 @@
program name is ``'/usr/local/bin/python'``, the exec-prefix is
``'/usr/local'``. The returned string points into static storage; the caller
should not modify its value. This corresponds to the :makevar:`exec_prefix`
- variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
+ variable in the top-level :file:`Makefile` and the ``--exec-prefix``
argument to the :program:`configure` script at build time. The value is
available to Python code as ``sys.exec_prefix``. It is only useful on Unix.
@@ -638,6 +638,16 @@
.. versionadded:: 2.3
+.. cfunction:: 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
+ always has such a thread-state, even if no auto-thread-state call has been
+ made on the main thread. This is mainly a helper/diagnostic function.
+
+ .. versionadded:: 2.3
+
+
The following macros are normally used without a trailing semicolon; look for
example usage in the Python source distribution.
@@ -881,7 +891,7 @@
modules.
Also note that combining this functionality with :cfunc:`PyGILState_\*` APIs
-is delicate, become these APIs assume a bijection between Python thread states
+is delicate, because these APIs assume a bijection between Python thread states
and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don't switch sub-interpreters between a pair
of matching :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls.
@@ -906,7 +916,7 @@
main thread where it has possession of the global interpreter lock and can
perform any Python API calls.
-.. cfunction:: void Py_AddPendingCall(int (*func)(void *), void *arg)
+.. cfunction:: int Py_AddPendingCall(int (*func)(void *), void *arg)
.. index:: single: Py_AddPendingCall()
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index a2e47d9..94af0f5 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -594,8 +594,8 @@
Compiling the interpreter with the :cmacro:`Py_DEBUG` macro defined produces
what is generally meant by "a debug build" of Python. :cmacro:`Py_DEBUG` is
-enabled in the Unix build by adding :option:`--with-pydebug` to the
-:file:`configure` command. It is also implied by the presence of the
+enabled in the Unix build by adding ``--with-pydebug`` to the
+:file:`./configure` command. It is also implied by the presence of the
not-Python-specific :cmacro:`_DEBUG` macro. When :cmacro:`Py_DEBUG` is enabled
in the Unix build, compiler optimization is disabled.
diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst
index abac599..649c723 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -107,7 +107,7 @@
.. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro)
Add an int constant to *module*. The name and the value are taken from
- *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int
+ *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int
constant *AF_INET* with the value of *AF_INET* to *module*.
Return ``-1`` on error, ``0`` on success.
diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst
index 6a538b3..717fb08 100644
--- a/Doc/c-api/object.rst
+++ b/Doc/c-api/object.rst
@@ -108,6 +108,9 @@
Python expression ``o1 op o2``, where ``op`` is the operator corresponding to
*opid*.
+.. note::
+ If *o1* and *o2* are the same object, :cfunc:`PyObject_RichCompareBool`
+ will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.
.. cfunction:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
diff --git a/Doc/c-api/sequence.rst b/Doc/c-api/sequence.rst
index 2808a88..25feac0 100644
--- a/Doc/c-api/sequence.rst
+++ b/Doc/c-api/sequence.rst
@@ -199,7 +199,7 @@
Return the *i*\ th element of *o* or *NULL* on failure. Macro form of
:cfunc:`PySequence_GetItem` but without checking that
- :cfunc:`PySequence_Check(o)` is true and without adjustment for negative
+ :cfunc:`PySequence_Check` on *o* is true and without adjustment for negative
indices.
.. versionadded:: 2.3
diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst
index 23f7c85..188fac8 100644
--- a/Doc/c-api/veryhigh.rst
+++ b/Doc/c-api/veryhigh.rst
@@ -32,11 +32,11 @@
prepared exactly as those which are passed to a C program's :cfunc:`main`
function. It is important to note that the argument list may be modified (but
the contents of the strings pointed to by the argument list are not). The return
- value will be the integer passed to the :func:`sys.exit` function, ``1`` if the
- interpreter exits due to an exception, or ``2`` if the parameter list does not
- represent a valid Python command line.
+ value will be ``0`` if the interpreter exits normally (ie, without an
+ exception), ``1`` if the interpreter exits due to an exception, or ``2``
+ if the parameter list does not represent a valid Python command line.
- Note that if an otherwise unhandled :exc:`SystemError` is raised, this
+ Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
function will not return ``1``, but exit the process, as long as
``Py_InspectFlag`` is not set.
@@ -82,7 +82,7 @@
there was an error, there is no way to get the exception information. For the
meaning of *flags*, see below.
- Note that if an otherwise unhandled :exc:`SystemError` is raised, this
+ Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
function will not return ``-1``, but exit the process, as long as
``Py_InspectFlag`` is not set.
diff --git a/Doc/distutils/apiref.rst b/Doc/distutils/apiref.rst
index b28a3af..eae9078 100644
--- a/Doc/distutils/apiref.rst
+++ b/Doc/distutils/apiref.rst
@@ -31,8 +31,9 @@
+====================+================================+=============================================================+
| *name* | The name of the package | a string |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *version* | The version number of the | See :mod:`distutils.version` |
- | | package | |
+ | *version* | The version number of the | a string |
+ | | package; see | |
+ | | :mod:`distutils.version` | |
+--------------------+--------------------------------+-------------------------------------------------------------+
| *description* | A single line describing the | a string |
| | package | |
@@ -49,14 +50,14 @@
| | maintainer, if different from | |
| | the author | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *maintainer_email* | The email address of the | |
+ | *maintainer_email* | The email address of the | a string |
| | current maintainer, if | |
| | different from the author | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *url* | A URL for the package | a URL |
+ | *url* | A URL for the package | a string |
| | (homepage) | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *download_url* | A URL to download the package | a URL |
+ | *download_url* | A URL to download the package | a string |
+--------------------+--------------------------------+-------------------------------------------------------------+
| *packages* | A list of Python packages that | a list of strings |
| | distutils will manipulate | |
@@ -68,14 +69,13 @@
| | files to be built and | |
| | installed | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *ext_modules* | A list of Python extensions to | A list of instances of |
+ | *ext_modules* | A list of Python extensions to | a list of instances of |
| | be built | :class:`distutils.core.Extension` |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *classifiers* | A list of categories for the | The list of available |
- | | package | categorizations is at |
- | | | http://pypi.python.org/pypi?:action=list_classifiers. |
+ | *classifiers* | A list of categories for the | a list of strings; valid classifiers are listed on `PyPI |
+ | | package | <http://pypi.python.org/pypi?:action=list_classifiers>`_. |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *distclass* | the :class:`Distribution` | A subclass of |
+ | *distclass* | the :class:`Distribution` | a subclass of |
| | class to use | :class:`distutils.core.Distribution` |
+--------------------+--------------------------------+-------------------------------------------------------------+
| *script_name* | The name of the setup.py | a string |
@@ -85,15 +85,15 @@
| *script_args* | Arguments to supply to the | a list of strings |
| | setup script | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *options* | default options for the setup | a string |
+ | *options* | default options for the setup | a dictionary |
| | script | |
+--------------------+--------------------------------+-------------------------------------------------------------+
| *license* | The license for the package | a string |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *keywords* | Descriptive meta-data, see | |
+ | *keywords* | Descriptive meta-data, see | a list of strings or a comma-separated string |
| | :pep:`314` | |
+--------------------+--------------------------------+-------------------------------------------------------------+
- | *platforms* | | |
+ | *platforms* | | a list of strings or a comma-separated string |
+--------------------+--------------------------------+-------------------------------------------------------------+
| *cmdclass* | A mapping of command names to | a dictionary |
| | :class:`Command` subclasses | |
@@ -147,11 +147,11 @@
In addition, the :mod:`distutils.core` module exposed a number of classes that
live elsewhere.
-* :class:`Extension` from :mod:`distutils.extension`
+* :class:`~distutils.extension.Extension` from :mod:`distutils.extension`
-* :class:`Command` from :mod:`distutils.cmd`
+* :class:`~distutils.cmd.Command` from :mod:`distutils.cmd`
-* :class:`Distribution` from :mod:`distutils.dist`
+* :class:`~distutils.dist.Distribution` from :mod:`distutils.dist`
A short description of each of these follows, but see the relevant module for
the full reference.
@@ -165,13 +165,13 @@
+------------------------+--------------------------------+---------------------------+
| argument name | value | type |
+========================+================================+===========================+
- | *name* | the full name of the | string |
+ | *name* | the full name of the | a string |
| | extension, including any | |
| | packages --- ie. *not* a | |
| | filename or pathname, but | |
| | Python dotted name | |
+------------------------+--------------------------------+---------------------------+
- | *sources* | list of source filenames, | string |
+ | *sources* | list of source filenames, | a list of strings |
| | relative to the distribution | |
| | root (where the setup script | |
| | lives), in Unix form (slash- | |
@@ -184,12 +184,12 @@
| | as source for a Python | |
| | extension. | |
+------------------------+--------------------------------+---------------------------+
- | *include_dirs* | list of directories to search | string |
+ | *include_dirs* | list of directories to search | a list of strings |
| | for C/C++ header files (in | |
| | Unix form for portability) | |
+------------------------+--------------------------------+---------------------------+
- | *define_macros* | list of macros to define; each | (string, string) tuple or |
- | | macro is defined using a | (name, ``None``) |
+ | *define_macros* | list of macros to define; each | a list of tuples |
+ | | macro is defined using a | |
| | 2-tuple ``(name, value)``, | |
| | where *value* is | |
| | either the string to define it | |
@@ -200,31 +200,31 @@
| | on Unix C compiler command | |
| | line) | |
+------------------------+--------------------------------+---------------------------+
- | *undef_macros* | list of macros to undefine | string |
+ | *undef_macros* | list of macros to undefine | a list of strings |
| | explicitly | |
+------------------------+--------------------------------+---------------------------+
- | *library_dirs* | list of directories to search | string |
+ | *library_dirs* | list of directories to search | a list of strings |
| | for C/C++ libraries at link | |
| | time | |
+------------------------+--------------------------------+---------------------------+
- | *libraries* | list of library names (not | string |
+ | *libraries* | list of library names (not | a list of strings |
| | filenames or paths) to link | |
| | against | |
+------------------------+--------------------------------+---------------------------+
- | *runtime_library_dirs* | list of directories to search | string |
+ | *runtime_library_dirs* | list of directories to search | a list of strings |
| | for C/C++ libraries at run | |
| | time (for shared extensions, | |
| | this is when the extension is | |
| | loaded) | |
+------------------------+--------------------------------+---------------------------+
- | *extra_objects* | list of extra files to link | string |
+ | *extra_objects* | list of extra files to link | a list of strings |
| | with (eg. object files not | |
| | implied by 'sources', static | |
| | library that must be | |
| | explicitly specified, binary | |
| | resource files, etc.) | |
+------------------------+--------------------------------+---------------------------+
- | *extra_compile_args* | any extra platform- and | string |
+ | *extra_compile_args* | any extra platform- and | a list of strings |
| | compiler-specific information | |
| | to use when compiling the | |
| | source files in 'sources'. For | |
@@ -235,7 +235,7 @@
| | for other platforms it could | |
| | be anything. | |
+------------------------+--------------------------------+---------------------------+
- | *extra_link_args* | any extra platform- and | string |
+ | *extra_link_args* | any extra platform- and | a list of strings |
| | compiler-specific information | |
| | to use when linking object | |
| | files together to create the | |
@@ -244,7 +244,7 @@
| | Similar interpretation as for | |
| | 'extra_compile_args'. | |
+------------------------+--------------------------------+---------------------------+
- | *export_symbols* | list of symbols to be exported | string |
+ | *export_symbols* | list of symbols to be exported | a list of strings |
| | from a shared extension. Not | |
| | used on all platforms, and not | |
| | generally necessary for Python | |
@@ -252,15 +252,20 @@
| | export exactly one symbol: | |
| | ``init`` + extension_name. | |
+------------------------+--------------------------------+---------------------------+
- | *depends* | list of files that the | string |
+ | *depends* | list of files that the | a list of strings |
| | extension depends on | |
+------------------------+--------------------------------+---------------------------+
- | *language* | extension language (i.e. | string |
+ | *language* | extension language (i.e. | a string |
| | ``'c'``, ``'c++'``, | |
| | ``'objc'``). Will be detected | |
| | from the source extensions if | |
| | not provided. | |
+------------------------+--------------------------------+---------------------------+
+ | *optional* | specifies that a build failure | a boolean |
+ | | in the extension should not | |
+ | | abort the build process, but | |
+ | | simply skip the extension. | |
+ +------------------------+--------------------------------+---------------------------+
.. class:: Distribution
@@ -1679,8 +1684,8 @@
===================================================================
.. module:: distutils.cmd
- :synopsis: This module provides the abstract base class Command. This class is subclassed
- by the modules in the distutils.command subpackage.
+ :synopsis: This module provides the abstract base class Command. This class
+ is subclassed by the modules in the distutils.command subpackage.
This module supplies the abstract base class :class:`Command`.
@@ -1690,20 +1695,84 @@
Abstract base class for defining command classes, the "worker bees" of the
Distutils. A useful analogy for command classes is to think of them as
- subroutines with local variables called *options*. The options are declared in
- :meth:`initialize_options` and defined (given their final values) in
- :meth:`finalize_options`, both of which must be defined by every command class.
- The distinction between the two is necessary because option values might come
- from the outside world (command line, config file, ...), and any options
- dependent on other options must be computed after these outside influences have
- been processed --- hence :meth:`finalize_options`. The body of the subroutine,
- where it does all its work based on the values of its options, is the
- :meth:`run` method, which must also be implemented by every command class.
+ subroutines with local variables called *options*. The options are declared
+ in :meth:`initialize_options` and defined (given their final values) in
+ :meth:`finalize_options`, both of which must be defined by every command
+ class. The distinction between the two is necessary because option values
+ might come from the outside world (command line, config file, ...), and any
+ options dependent on other options must be computed after these outside
+ influences have been processed --- hence :meth:`finalize_options`. The body
+ of the subroutine, where it does all its work based on the values of its
+ options, is the :meth:`run` method, which must also be implemented by every
+ command class.
- The class constructor takes a single argument *dist*, a :class:`Distribution`
+ The class constructor takes a single argument *dist*, a :class:`Distribution`
instance.
+Creating a new Distutils command
+================================
+
+This section outlines the steps to create a new Distutils command.
+
+A new command lives in a module in the :mod:`distutils.command` package. There
+is a sample template in that directory called :file:`command_template`. Copy
+this file to a new module with the same name as the new command you're
+implementing. This module should implement a class with the same name as the
+module (and the command). So, for instance, to create the command
+``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy
+:file:`command_template` to :file:`distutils/command/peel_banana.py`, then edit
+it so that it's implementing the class :class:`peel_banana`, a subclass of
+:class:`distutils.cmd.Command`.
+
+Subclasses of :class:`Command` must define the following methods.
+
+.. method:: Command.initialize_options()
+
+ Set default values for all the options that this command supports. Note that
+ these defaults may be overridden by other commands, by the setup script, by
+ config files, or by the command-line. Thus, this is not the place to code
+ dependencies between options; generally, :meth:`initialize_options`
+ implementations are just a bunch of ``self.foo = None`` assignments.
+
+
+.. method:: Command.finalize_options()
+
+ Set final values for all the options that this command supports. This is
+ always called as late as possible, ie. after any option assignments from the
+ command-line or from other commands have been done. Thus, this is the place
+ to to code option dependencies: if *foo* depends on *bar*, then it is safe to
+ set *foo* from *bar* as long as *foo* still has the same value it was
+ assigned in :meth:`initialize_options`.
+
+
+.. method:: Command.run()
+
+ A command's raison d'etre: carry out the action it exists to perform, controlled
+ by the options initialized in :meth:`initialize_options`, customized by other
+ commands, the setup script, the command-line, and config files, and finalized in
+ :meth:`finalize_options`. All terminal output and filesystem interaction should
+ be done by :meth:`run`.
+
+
+.. attribute:: Command.sub_commands
+
+ *sub_commands* formalizes the notion of a "family" of commands,
+ e.g. ``install`` as the parent with sub-commands ``install_lib``,
+ ``install_headers``, etc. The parent of a family of commands defines
+ *sub_commands* as a class attribute; it's a list of 2-tuples ``(command_name,
+ predicate)``, with *command_name* a string and *predicate* a function, a
+ string or ``None``. *predicate* is a method of the parent command that
+ determines whether the corresponding command is applicable in the current
+ situation. (E.g. ``install_headers`` is only applicable if we have any C
+ header files to install.) If *predicate* is ``None``, that command is always
+ applicable.
+
+ *sub_commands* is usually defined at the *end* of a class, because
+ predicates can be methods of the class, so they must already have been
+ defined. The canonical example is the :command:`install` command.
+
+
:mod:`distutils.command` --- Individual Distutils commands
==========================================================
@@ -1751,7 +1820,7 @@
.. module:: distutils.command.bdist_msi
:synopsis: Build a binary distribution as a Windows MSI file
-.. class:: bdist_msi(Command)
+.. class:: bdist_msi
Builds a `Windows Installer`_ (.msi) binary package.
@@ -1926,61 +1995,15 @@
.. % todo
-Creating a new Distutils command
-================================
+:mod:`distutils.command.check` --- Check the meta-data of a package
+===================================================================
-This section outlines the steps to create a new Distutils command.
-
-A new command lives in a module in the :mod:`distutils.command` package. There
-is a sample template in that directory called :file:`command_template`. Copy
-this file to a new module with the same name as the new command you're
-implementing. This module should implement a class with the same name as the
-module (and the command). So, for instance, to create the command
-``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy
-:file:`command_template` to :file:`distutils/command/peel_banana.py`, then edit
-it so that it's implementing the class :class:`peel_banana`, a subclass of
-:class:`distutils.cmd.Command`.
-
-Subclasses of :class:`Command` must define the following methods.
+.. module:: distutils.command.check
+ :synopsis: Check the metadata of a package
-.. method:: Command.initialize_options()
+The ``check`` command performs some tests on the meta-data of a package.
+For example, it verifies that all required meta-data are provided as
+the arguments passed to the :func:`setup` function.
- Set default values for all the options that this command supports. Note that
- these defaults may be overridden by other commands, by the setup script, by
- config files, or by the command-line. Thus, this is not the place to code
- dependencies between options; generally, :meth:`initialize_options`
- implementations are just a bunch of ``self.foo = None`` assignments.
-
-
-.. method:: Command.finalize_options()
-
- Set final values for all the options that this command supports. This is
- always called as late as possible, ie. after any option assignments from the
- command-line or from other commands have been done. Thus, this is the place
- to to code option dependencies: if *foo* depends on *bar*, then it is safe to
- set *foo* from *bar* as long as *foo* still has the same value it was
- assigned in :meth:`initialize_options`.
-
-
-.. method:: Command.run()
-
- A command's raison d'etre: carry out the action it exists to perform, controlled
- by the options initialized in :meth:`initialize_options`, customized by other
- commands, the setup script, the command-line, and config files, and finalized in
- :meth:`finalize_options`. All terminal output and filesystem interaction should
- be done by :meth:`run`.
-
-*sub_commands* formalizes the notion of a "family" of commands, eg. ``install``
-as the parent with sub-commands ``install_lib``, ``install_headers``, etc. The
-parent of a family of commands defines *sub_commands* as a class attribute; it's
-a list of 2-tuples ``(command_name, predicate)``, with *command_name* a string
-and *predicate* an unbound method, a string or None. *predicate* is a method of
-the parent command that determines whether the corresponding command is
-applicable in the current situation. (Eg. we ``install_headers`` is only
-applicable if we have any C header files to install.) If *predicate* is None,
-that command is always applicable.
-
-*sub_commands* is usually defined at the \*end\* of a class, because predicates
-can be unbound methods, so they must already have been defined. The canonical
-example is the :command:`install` command.
+.. % todo
diff --git a/Doc/distutils/introduction.rst b/Doc/distutils/introduction.rst
index b772b01..fc6184f 100644
--- a/Doc/distutils/introduction.rst
+++ b/Doc/distutils/introduction.rst
@@ -79,11 +79,17 @@
for an example)
To create a source distribution for this module, you would create a setup
-script, :file:`setup.py`, containing the above code, and run::
+script, :file:`setup.py`, containing the above code, and run this command from a
+terminal::
python setup.py sdist
-which will create an archive file (e.g., tarball on Unix, ZIP file on Windows)
+For Windows, open a command prompt windows (:menuselection:`Start -->
+Accessories`) and change the command to::
+
+ setup.py sdist
+
+:command:`sdist` will create an archive file (e.g., tarball on Unix, ZIP file on Windows)
containing your setup script :file:`setup.py`, and your module :file:`foo.py`.
The archive file will be named :file:`foo-1.0.tar.gz` (or :file:`.zip`), and
will unpack into a directory :file:`foo-1.0`.
diff --git a/Doc/distutils/setupscript.rst b/Doc/distutils/setupscript.rst
index e457918..cce78b0 100644
--- a/Doc/distutils/setupscript.rst
+++ b/Doc/distutils/setupscript.rst
@@ -72,7 +72,7 @@
promising that the Distutils will find a file :file:`foo/__init__.py` (which
might be spelled differently on your system, but you get the idea) relative to
the directory where your setup script lives. If you break this promise, the
-Distutils will issue a warning but still process the broken package anyways.
+Distutils will issue a warning but still process the broken package anyway.
If you use a different convention to lay out your source directory, that's no
problem: you just have to supply the :option:`package_dir` option to tell the
@@ -254,7 +254,7 @@
If you need to include header files from some other Python extension, you can
take advantage of the fact that header files are installed in a consistent way
-by the Distutils :command:`install_header` command. For example, the Numerical
+by the Distutils :command:`install_headers` command. For example, the Numerical
Python header files are installed (on a standard Unix installation) to
:file:`/usr/local/include/python1.5/Numerical`. (The exact location will differ
according to your platform and Python installation.) Since the Python include
diff --git a/Doc/distutils/sourcedist.rst b/Doc/distutils/sourcedist.rst
index fc860de..a9858d0 100644
--- a/Doc/distutils/sourcedist.rst
+++ b/Doc/distutils/sourcedist.rst
@@ -111,12 +111,22 @@
:file:`MANIFEST`, you must specify everything: the default set of files
described above does not apply in this case.
-.. versionadded:: 2.7
+.. versionchanged:: 2.7
+ An existing generated :file:`MANIFEST` will be regenerated without
+ :command:`sdist` comparing its modification time to the one of
+ :file:`MANIFEST.in` or :file:`setup.py`.
+
+.. versionchanged:: 2.7.1
:file:`MANIFEST` files start with a comment indicating they are generated.
Files without this comment are not overwritten or removed.
+.. versionchanged:: 2.7.3
+ :command:`sdist` will read a :file:`MANIFEST` file if no :file:`MANIFEST.in`
+ exists, like it did before 2.7.
+
See :ref:`manifest_template` section for a syntax reference.
+
.. _manifest-options:
Manifest-related options
@@ -124,16 +134,16 @@
The normal course of operations for the :command:`sdist` command is as follows:
-* if the manifest file, :file:`MANIFEST` doesn't exist, read :file:`MANIFEST.in`
- and create the manifest
+* if the manifest file (:file:`MANIFEST` by default) exists and the first line
+ does not have a comment indicating it is generated from :file:`MANIFEST.in`,
+ then it is used as is, unaltered
+
+* if the manifest file doesn't exist or has been previously automatically
+ generated, read :file:`MANIFEST.in` and create the manifest
* if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest
with just the default file set
-* if either :file:`MANIFEST.in` or the setup script (:file:`setup.py`) are more
- recent than :file:`MANIFEST`, recreate :file:`MANIFEST` by reading
- :file:`MANIFEST.in`
-
* use the list of files now in :file:`MANIFEST` (either just generated or read
in) to create the source distribution archive(s)
@@ -271,8 +281,3 @@
``a-z``, ``a-zA-Z``, ``a-f0-9_.``). The definition of "regular filename
character" is platform-specific: on Unix it is anything except slash; on Windows
anything except backslash or colon.
-
-.. versionchanged:: 2.7
- An existing generated :file:`MANIFEST` will be regenerated without
- :command:`sdist` comparing its modification time to the one of
- :file:`MANIFEST.in` or :file:`setup.py`.
diff --git a/Doc/documenting/building.rst b/Doc/documenting/building.rst
index 9ab2519..dc1c6a0 100644
--- a/Doc/documenting/building.rst
+++ b/Doc/documenting/building.rst
@@ -14,11 +14,12 @@
Luckily, a Makefile has been prepared so that on Unix, provided you have
installed Python and Subversion, you can just run ::
+ cd Doc
make html
-to check out the necessary toolset in the `tools/` subdirectory and build the
-HTML output files. To view the generated HTML, point your favorite browser at
-the top-level index `build/html/index.html` after running "make".
+to check out the necessary toolset in the :file:`tools/` subdirectory and build
+the HTML output files. To view the generated HTML, point your favorite browser
+at the top-level index :file:`build/html/index.html` after running "make".
Available make targets are:
@@ -49,10 +50,10 @@
* "pydoc-topics", which builds a Python module containing a dictionary with
plain text documentation for the labels defined in
- `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and
+ :file:`tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and
keyword help.
-A "make update" updates the Subversion checkouts in `tools/`.
+A "make update" updates the Subversion checkouts in :file:`tools/`.
Without make
diff --git a/Doc/documenting/markup.rst b/Doc/documenting/markup.rst
index d7d23cd..25801c7 100644
--- a/Doc/documenting/markup.rst
+++ b/Doc/documenting/markup.rst
@@ -98,11 +98,12 @@
Spam or ham the foo.
-The signatures of object methods or data attributes should always include the
-type name (``.. method:: FileInput.input(...)``), even if it is obvious from the
-context which type they belong to; this is to enable consistent
-cross-references. If you describe methods belonging to an abstract protocol,
-such as "context managers", include a (pseudo-)type name too to make the
+The signatures of object methods or data attributes should not include the
+class name, but be nested in a class directive. The generated files will
+reflect this nesting, and the target identifiers (for HTML output) will use
+both the class and method name, to enable consistent cross-references. If you
+describe methods belonging to an abstract protocol such as context managers,
+use a class directive with a (pseudo-)type name too to make the
index entries more informative.
The directives are:
@@ -152,7 +153,7 @@
Describes global data in a module, including both variables and values used
as "defined constants." Class and object attributes are not documented
- using this environment.
+ using this directive.
.. describe:: exception
@@ -165,7 +166,7 @@
parameters, enclosing optional parameters in brackets. Default values can be
given if it enhances clarity. For example::
- .. function:: Timer.repeat([repeat=3[, number=1000000]])
+ .. function:: repeat([repeat=3[, number=1000000]])
Object methods are not documented using this directive. Bound object methods
placed in the module namespace as part of the public interface of the module
@@ -186,13 +187,30 @@
Describes an object data attribute. The description should include
information about the type of the data to be expected and whether it may be
- changed directly.
+ changed directly. This directive should be nested in a class directive,
+ like in this example::
+
+ .. class:: Spam
+
+ Description of the class.
+
+ .. data:: ham
+
+ Description of the attribute.
+
+ If is also possible to document an attribute outside of a class directive,
+ for example if the documentation for different attributes and methods is
+ split in multiple sections. The class name should then be included
+ explicitly::
+
+ .. data:: Spam.eggs
.. describe:: method
Describes an object method. The parameters should not include the ``self``
parameter. The description should include similar information to that
- described for ``function``.
+ described for ``function``. This directive should be nested in a class
+ directive, like in the example above.
.. describe:: opcode
@@ -454,7 +472,10 @@
.. describe:: keyword
- The name of a keyword in Python.
+ The name of a Python keyword. Using this role will generate a link to the
+ documentation of the keyword. ``True``, ``False`` and ``None`` do not use
+ this role, but simple code markup (````True````), given that they're
+ fundamental to the language and should be known to any programmer.
.. describe:: mailheader
diff --git a/Doc/documenting/style.rst b/Doc/documenting/style.rst
index c3dded9..1928940 100644
--- a/Doc/documenting/style.rst
+++ b/Doc/documenting/style.rst
@@ -65,6 +65,110 @@
The name of the operating system developed at AT&T Bell Labs in the early
1970s.
+Affirmative Tone
+----------------
+
+The documentation focuses on affirmatively stating what the language does and
+how to use it effectively.
+
+Except for certain security risks or segfault risks, the docs should avoid
+wording along the lines of "feature x is dangerous" or "experts only". These
+kinds of value judgments belong in external blogs and wikis, not in the core
+documentation.
+
+Bad example (creating worry in the mind of a reader):
+
+ Warning: failing to explicitly close a file could result in lost data or
+ excessive resource consumption. Never rely on reference counting to
+ automatically close a file.
+
+Good example (establishing confident knowledge in the effective use of the language):
+
+ A best practice for using files is use a try/finally pair to explicitly
+ close a file after it is used. Alternatively, using a with-statement can
+ achieve the same effect. This assures that files are flushed and file
+ descriptor resources are released in a timely manner.
+
+Economy of Expression
+---------------------
+
+More documentation is not necessarily better documentation. Err on the side
+of being succinct.
+
+It is an unfortunate fact that making documentation longer can be an impediment
+to understanding and can result in even more ways to misread or misinterpret the
+text. Long descriptions full of corner cases and caveats can create the
+impression that a function is more complex or harder to use than it actually is.
+
+The documentation for :func:`super` is an example of where a good deal of
+information was condensed into a few short paragraphs. Discussion of
+:func:`super` could have filled a chapter in a book, but it is often easier to
+grasp a terse description than a lengthy narrative.
+
+
+Code Examples
+-------------
+
+Short code examples can be a useful adjunct to understanding. Readers can often
+grasp a simple example more quickly than they can digest a formal description in
+prose.
+
+People learn faster with concrete, motivating examples that match the context of
+a typical use case. For instance, the :func:`str.rpartition` method is better
+demonstrated with an example splitting the domain from a URL than it would be
+with an example of removing the last word from a line of Monty Python dialog.
+
+The ellipsis for the :attr:`sys.ps2` secondary interpreter prompt should only be
+used sparingly, where it is necessary to clearly differentiate between input
+lines and output lines. Besides contributing visual clutter, it makes it
+difficult for readers to cut-and-paste examples so they can experiment with
+variations.
+
+Code Equivalents
+----------------
+
+Giving pure Python code equivalents (or approximate equivalents) can be a useful
+adjunct to a prose description. A documenter should carefully weigh whether the
+code equivalent adds value.
+
+A good example is the code equivalent for :func:`all`. The short 4-line code
+equivalent is easily digested; it re-emphasizes the early-out behavior; and it
+clarifies the handling of the corner-case where the iterable is empty. In
+addition, it serves as a model for people wanting to implement a commonly
+requested alternative where :func:`all` would return the specific object
+evaluating to False whenever the function terminates early.
+
+A more questionable example is the code for :func:`itertools.groupby`. Its code
+equivalent borders on being too complex to be a quick aid to understanding.
+Despite its complexity, the code equivalent was kept because it serves as a
+model to alternative implementations and because the operation of the "grouper"
+is more easily shown in code than in English prose.
+
+An example of when not to use a code equivalent is for the :func:`oct` function.
+The exact steps in converting a number to octal doesn't add value for a user
+trying to learn what the function does.
+
+Audience
+--------
+
+The tone of the tutorial (and all the docs) needs to be respectful of the
+reader's intelligence. Don't presume that the readers are stupid. Lay out the
+relevant information, show motivating use cases, provide glossary links, and do
+your best to connect the dots, but don't talk down to them or waste their time.
+
+The tutorial is meant for newcomers, many of whom will be using the tutorial to
+evaluate the language as a whole. The experience needs to be positive and not
+leave the reader with worries that something bad will happen if they make a
+misstep. The tutorial serves as guide for intelligent and curious readers,
+saving details for the how-to guides and other sources.
+
+Be careful accepting requests for documentation changes from the rare but vocal
+category of reader who is looking for vindication for one of their programming
+errors ("I made a mistake, therefore the docs must be wrong ..."). Typically,
+the documentation wasn't consulted until after the error was made. It is
+unfortunate, but typically no documentation edit would have saved the user from
+making false assumptions about the language ("I was surprised by ...").
+
.. _Apple Publications Style Guide: http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2009.pdf
diff --git a/Doc/extending/newtypes.rst b/Doc/extending/newtypes.rst
index fb2c15a..f4c3c02 100644
--- a/Doc/extending/newtypes.rst
+++ b/Doc/extending/newtypes.rst
@@ -38,8 +38,7 @@
just contains the refcount and a pointer to the object's "type object". This is
where the action is; the type object determines which (C) functions get called
when, for instance, an attribute gets looked up on an object or it is multiplied
-by another object. These C functions are called "type methods" to distinguish
-them from things like ``[].append`` (which we call "object methods").
+by another object. These C functions are called "type methods".
So, if you want to define a new object type, you need to create a new type
object.
diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst
index 0943796..962b4ef 100644
--- a/Doc/faq/design.rst
+++ b/Doc/faq/design.rst
@@ -684,7 +684,7 @@
Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes
(ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check
whether an instance or a class implements a particular ABC. The
-:mod:`collections` modules defines a set of useful ABCs such as
+:mod:`collections` module defines a set of useful ABCs such as
:class:`Iterable`, :class:`Container`, and :class:`MutableMapping`.
For Python, many of the advantages of interface specifications can be obtained
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index e53facd..268b918 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -171,7 +171,7 @@
Thus to get the same effect as::
L2 = []
- for i in range[3]:
+ for i in range(3):
L2.append(L1[i])
it is much shorter and far faster to use ::
diff --git a/Doc/faq/windows.rst b/Doc/faq/windows.rst
index 47c09ad..96d1c51 100644
--- a/Doc/faq/windows.rst
+++ b/Doc/faq/windows.rst
@@ -542,7 +542,7 @@
:func:`execfile` with the name of your file as argument.
Also note that you can not mix-and-match Debug and Release versions. If you
-wish to use the Debug Multithreaded DLL, then your module *must* have an "_d"
+wish to use the Debug Multithreaded DLL, then your module *must* have ``_d``
appended to the base name.
diff --git a/Doc/glossary.rst b/Doc/glossary.rst
index 7822634..37fa9b0 100644
--- a/Doc/glossary.rst
+++ b/Doc/glossary.rst
@@ -27,12 +27,16 @@
:ref:`2to3-reference`.
abstract base class
- :ref:`abstract-base-classes` complement :term:`duck-typing` by
+ Abstract base classes complement :term:`duck-typing` by
providing a way to define interfaces when other techniques like
- :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for
+ :func:`hasattr` would be clumsy or subtly wrong (for example with
+ :ref:`magic methods <new-style-special-lookup>`). ABCs introduce virtual
+ subclasses, which are classes that don't inherit from a class but are
+ still recognized by :func:`isinstance` and :func:`issubclass`; see the
+ :mod:`abc` module documentation. Python comes with many built-in ABCs for
data structures (in the :mod:`collections` module), numbers (in the
:mod:`numbers` module), and streams (in the :mod:`io` module). You can
- create your own ABC with the :mod:`abc` module.
+ create your own ABCs with the :mod:`abc` module.
argument
A value passed to a function or method, assigned to a named local
@@ -57,11 +61,14 @@
bytecode
Python source code is compiled into bytecode, the internal representation
- of a Python program in the interpreter. The bytecode is also cached in
- ``.pyc`` and ``.pyo`` files so that executing the same file is faster the
- second time (recompilation from source to bytecode can be avoided). This
- "intermediate language" is said to run on a :term:`virtual machine`
- that executes the machine code corresponding to each bytecode.
+ of a Python program in the CPython interpreter. The bytecode is also
+ cached in ``.pyc`` and ``.pyo`` files so that executing the same file is
+ faster the second time (recompilation from source to bytecode can be
+ avoided). This "intermediate language" is said to run on a
+ :term:`virtual machine` that executes the machine code corresponding to
+ each bytecode. Do note that bytecodes are not expected to work between
+ different Python virtual machines, nor to be stable between Python
+ releases.
A list of bytecode instructions can be found in the documentation for
:ref:`the dis module <bytecodes>`.
@@ -127,8 +134,9 @@
def f(...):
...
- See :ref:`the documentation for function definition <function>` for more
- about decorators.
+ The same concept exists for classes, but is less commonly used there. See
+ the documentation for :ref:`function definitions <function>` and
+ :ref:`class definitions <class>` for more about decorators.
descriptor
Any *new-style* object which defines the methods :meth:`__get__`,
@@ -164,8 +172,8 @@
well-designed code improves its flexibility by allowing polymorphic
substitution. Duck-typing avoids tests using :func:`type` or
:func:`isinstance`. (Note, however, that duck-typing can be complemented
- with :term:`abstract base class`\ es.) Instead, it typically employs
- :func:`hasattr` tests or :term:`EAFP` programming.
+ with :term:`abstract base classes <abstract base class>`.) Instead, it
+ typically employs :func:`hasattr` tests or :term:`EAFP` programming.
EAFP
Easier to ask for forgiveness than permission. This common Python coding
@@ -177,17 +185,34 @@
expression
A piece of syntax which can be evaluated to some value. In other words,
- an expression is an accumulation of expression elements like literals, names,
- attribute access, operators or function calls which all return a value.
- In contrast to many other languages, not all language constructs are expressions.
- There are also :term:`statement`\s which cannot be used as expressions,
- such as :keyword:`print` or :keyword:`if`. Assignments are also statements,
- not expressions.
+ an expression is an accumulation of expression elements like literals,
+ names, attribute access, operators or function calls which all return a
+ value. In contrast to many other languages, not all language constructs
+ are expressions. There are also :term:`statement`\s which cannot be used
+ as expressions, such as :keyword:`print` or :keyword:`if`. Assignments
+ are also statements, not expressions.
extension module
A module written in C or C++, using Python's C API to interact with the
core and with user code.
+ file object
+ An object exposing a file-oriented API (with methods such as
+ :meth:`read()` or :meth:`write()`) to an underlying resource. Depending
+ on the way it was created, a file object can mediate access to a real
+ on-disk file or to another other type of storage or communication device
+ (for example standard input/output, in-memory buffers, sockets, pipes,
+ etc.). File objects are also called :dfn:`file-like objects` or
+ :dfn:`streams`.
+
+ There are actually three categories of file objects: raw binary files,
+ buffered binary files and text files. Their interfaces are defined in the
+ :mod:`io` module. The canonical way to create a file object is by using
+ the :func:`open` function.
+
+ file-like object
+ A synonym for :term:`file object`.
+
finder
An object that tries to find the :term:`loader` for a module. It must
implement a method named :meth:`find_module`. See :pep:`302` for
@@ -334,7 +359,7 @@
slowly. See also :term:`interactive`.
iterable
- A container object capable of returning its members one at a
+ An object capable of returning its members one at a
time. Examples of iterables include all sequence types (such as
:class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence
types like :class:`dict` and :class:`file` and objects of any classes you
@@ -392,26 +417,6 @@
value is assigned. ``**`` is used to accept or pass a dictionary of
keyword arguments. See :term:`argument`.
- key function
- A key function or collation function is a callable that returns a value
- used for sorting or ordering. For example, :func:`locale.strxfrm` is
- used to produce a sort key that is aware of locale specific sort
- conventions.
-
- A number of tools in Python accept key functions to control how elements
- are ordered or grouped. They include :func:`min`, :func:`max`,
- :func:`sorted`, :meth:`list.sort`, :func:`heapq.nsmallest`,
- :func:`heapq.nlargest`, and :func:`itertools.groupby`.
-
- There are several ways to create a key function. For example. the
- :meth:`str.lower` method can serve as a key function for case insensitive
- sorts. Alternatively, an ad-hoc key function can be built from a
- :keyword:`lambda` expression such as ``lambda r: (r[0], r[2])``. Also,
- the :mod:`operator` module provides three key function constuctors:
- :func:`~operator.attrgetter`, :func:`~operator.itemgetter`, and
- :func:`~operator.methodcaller`. See the :ref:`sortinghowto` for
- examples of how to create and use key functions.
-
lambda
An anonymous inline function consisting of a single :term:`expression`
which is evaluated when the function is called. The syntax to create
@@ -423,6 +428,12 @@
the :term:`EAFP` approach and is characterized by the presence of many
:keyword:`if` statements.
+ In a multi-threaded environment, the LBYL approach can risk introducing a
+ race condition between "the looking" and "the leaping". For example, the
+ code, ``if key in mapping: return mapping[key]`` can fail if another
+ thread removes *key* from *mapping* after the test, but before the lookup.
+ This issue can be solved with locks or by using the EAFP approach.
+
list
A built-in Python :term:`sequence`. Despite its name it is more akin
to an array in other languages than to a linked list since access to
@@ -443,9 +454,10 @@
mapping
A container object that supports arbitrary key lookups and implements the
- methods specified in the :class:`Mapping` or :class:`MutableMapping`
- :ref:`abstract base classes <abstract-base-classes>`. Examples include
- :class:`dict`, :class:`collections.defaultdict`,
+ methods specified in the :class:`~collections.Mapping` or
+ :class:`~collections.MutableMapping`
+ :ref:`abstract base classes <collections-abstract-base-classes>`. Examples
+ include :class:`dict`, :class:`collections.defaultdict`,
:class:`collections.OrderedDict` and :class:`collections.Counter`.
metaclass
@@ -467,6 +479,14 @@
its first :term:`argument` (which is usually called ``self``).
See :term:`function` and :term:`nested scope`.
+ method resolution order
+ Method Resolution Order is the order in which base classes are searched
+ for a member during lookup. See `The Python 2.3 Method Resolution Order
+ <http://www.python.org/download/releases/2.3/mro/>`_.
+
+ MRO
+ See :term:`method resolution order`.
+
mutable
Mutable objects can change their value but keep their :func:`id`. See
also :term:`immutable`.
@@ -499,10 +519,11 @@
nested scope
The ability to refer to a variable in an enclosing definition. For
instance, a function defined inside another function can refer to
- variables in the outer function. Note that nested scopes work only for
- reference and not for assignment which will always write to the innermost
- scope. In contrast, local variables both read and write in the innermost
- scope. Likewise, global variables read and write to the global namespace.
+ variables in the outer function. Note that nested scopes by default work
+ only for reference and not for assignment. Local variables both read and
+ write in the innermost scope. Likewise, global variables read and write
+ to the global namespace. The :keyword:`nonlocal` allows writing to outer
+ scopes.
new-style class
Any class which inherits from :class:`object`. This includes all built-in
@@ -525,9 +546,9 @@
:term:`argument`.
Python 3000
- Nickname for the next major Python version, 3.0 (coined long ago
- when the release of version 3 was something in the distant future.) This
- is also abbreviated "Py3k".
+ Nickname for the Python 3.x release line (coined long ago when the release
+ of version 3 was something in the distant future.) This is also
+ abbreviated "Py3k".
Pythonic
An idea or piece of code which closely follows the most common idioms
@@ -550,7 +571,7 @@
object drops to zero, it is deallocated. Reference counting is
generally not visible to Python code, but it is a key element of the
:term:`CPython` implementation. The :mod:`sys` module defines a
- :func:`getrefcount` function that programmers can call to return the
+ :func:`~sys.getrefcount` function that programmers can call to return the
reference count for a particular object.
__slots__
@@ -586,7 +607,15 @@
statement
A statement is part of a suite (a "block" of code). A statement is either
an :term:`expression` or a one of several constructs with a keyword, such
- as :keyword:`if`, :keyword:`while` or :keyword:`print`.
+ as :keyword:`if`, :keyword:`while` or :keyword:`for`.
+
+ struct sequence
+ A tuple with named elements. Struct sequences expose an interface similiar
+ to :term:`named tuple` in that elements can either be accessed either by
+ index or as an attribute. However, they do not have any of the named tuple
+ methods like :meth:`~collections.somenamedtuple._make` or
+ :meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences
+ include :data:`sys.float_info` and the return value of :func:`os.stat`.
triple-quoted string
A string which is bound by three instances of either a quotation mark
diff --git a/Doc/howto/advocacy.rst b/Doc/howto/advocacy.rst
index d71e1ec..e67e201 100644
--- a/Doc/howto/advocacy.rst
+++ b/Doc/howto/advocacy.rst
@@ -308,7 +308,7 @@
buying, but the publishers have made the first chapter available on
the Web.
-http://home.pacbell.net/ouster/scripting.html
+http://www.tcl.tk/doc/scripting.html
John Ousterhout's white paper on scripting is a good argument for the utility of
scripting languages, though naturally enough, he emphasizes Tcl, the language he
developed. Most of the arguments would apply to any scripting language.
diff --git a/Doc/howto/cporting.rst b/Doc/howto/cporting.rst
index 8030f13..5ba5df7 100644
--- a/Doc/howto/cporting.rst
+++ b/Doc/howto/cporting.rst
@@ -1,5 +1,7 @@
.. highlightlang:: c
+.. _cporting-howto:
+
********************************
Porting Extension Modules to 3.0
********************************
@@ -207,6 +209,58 @@
}
+CObject replaced with Capsule
+=============================
+
+The :ctype:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
+:ctype:`CObject`. CObjects were useful,
+but the :ctype:`CObject` API was problematic: it didn't permit distinguishing
+between valid CObjects, which allowed mismatched CObjects to crash the
+interpreter, and some of its APIs relied on undefined behavior in C.
+(For further reading on the rationale behind Capsules, please see :issue:`5630`.)
+
+If you're currently using CObjects, and you want to migrate to 3.1 or newer,
+you'll need to switch to Capsules.
+:ctype:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
+Python 3.2. If you only support 2.7, or 3.1 and above, you
+can simply switch to :ctype:`Capsule`. If you need to support 3.0 or
+versions of Python earlier than 2.7 you'll have to support both CObjects
+and Capsules.
+
+The following example header file :file:`capsulethunk.h` may
+solve the problem for you;
+simply write your code against the :ctype:`Capsule` API, include
+this header file after ``"Python.h"``, and you'll automatically use CObjects
+in Python 3.0 or versions earlier than 2.7.
+
+:file:`capsulethunk.h` simulates Capsules using CObjects. However,
+:ctype:`CObject` provides no place to store the capsule's "name". As a
+result the simulated :ctype:`Capsule` objects created by :file:`capsulethunk.h`
+behave slightly differently from real Capsules. Specifically:
+
+ * The name parameter passed in to :cfunc:`PyCapsule_New` is ignored.
+
+ * The name parameter passed in to :cfunc:`PyCapsule_IsValid` and
+ :cfunc:`PyCapsule_GetPointer` is ignored, and no error checking
+ of the name is performed.
+
+ * :cfunc:`PyCapsule_GetName` always returns NULL.
+
+ * :cfunc:`PyCapsule_SetName` always throws an exception and
+ returns failure. (Since there's no way to store a name
+ in a CObject, noisy failure of :cfunc:`PyCapsule_SetName`
+ was deemed preferable to silent failure here. If this is
+ inconveient, feel free to modify your local
+ copy as you see fit.)
+
+You can find :file:`capsulethunk.h` in the Python source distribution
+in the :file:`Doc/includes` directory. We also include it here for
+your reference; here is :file:`capsulethunk.h`:
+
+.. literalinclude:: ../includes/capsulethunk.h
+
+
+
Other options
=============
diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst
index 55a1d62..78c1439 100644
--- a/Doc/howto/descriptor.rst
+++ b/Doc/howto/descriptor.rst
@@ -42,7 +42,7 @@
Descriptors are a powerful, general purpose protocol. They are the mechanism
behind properties, methods, static methods, class methods, and :func:`super()`.
-They are used used throughout Python itself to implement the new style classes
+They are used throughout Python itself to implement the new style classes
introduced in version 2.2. Descriptors simplify the underlying C-code and offer
a flexible set of new tools for everyday Python programs.
diff --git a/Doc/howto/doanddont.rst b/Doc/howto/doanddont.rst
index 2e9e0b8..98dbad1 100644
--- a/Doc/howto/doanddont.rst
+++ b/Doc/howto/doanddont.rst
@@ -32,8 +32,8 @@
versions of Python do not check for the invalidity, it does not make it more
valid, no more than having a smart lawyer makes a man innocent. Do not use it
like that ever. Even in versions where it was accepted, it made the function
-execution slower, because the compiler could not be certain which names are
-local and which are global. In Python 2.1 this construct causes warnings, and
+execution slower, because the compiler could not be certain which names were
+local and which were global. In Python 2.1 this construct causes warnings, and
sometimes even errors.
@@ -46,7 +46,7 @@
in your favourite editor. You also open yourself to trouble in the future, if
some module grows additional functions or classes.
-One of the most awful question asked on the newsgroup is why this code::
+One of the most awful questions asked on the newsgroup is why this code::
f = open("www")
f.read()
@@ -113,7 +113,7 @@
This is a "don't" which is much weaker than the previous "don't"s but is still
something you should not do if you don't have good reasons to do that. The
-reason it is usually bad idea is because you suddenly have an object which lives
+reason it is usually a bad idea is because you suddenly have an object which lives
in two separate namespaces. When the binding in one namespace changes, the
binding in the other will not, so there will be a discrepancy between them. This
happens when, for example, one module is reloaded, or changes the definition of
diff --git a/Doc/howto/index.rst b/Doc/howto/index.rst
index 09bc5cb..94ecc9a 100644
--- a/Doc/howto/index.rst
+++ b/Doc/howto/index.rst
@@ -14,6 +14,7 @@
:maxdepth: 1
advocacy.rst
+ pyporting.rst
cporting.rst
curses.rst
descriptor.rst
diff --git a/Doc/howto/logging.rst b/Doc/howto/logging.rst
index 6fb8081..029a0ab 100644
--- a/Doc/howto/logging.rst
+++ b/Doc/howto/logging.rst
@@ -670,7 +670,7 @@
version: 1
formatters:
simple:
- format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
+ format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
diff --git a/Doc/howto/pyporting.rst b/Doc/howto/pyporting.rst
new file mode 100644
index 0000000..124ef33
--- /dev/null
+++ b/Doc/howto/pyporting.rst
@@ -0,0 +1,703 @@
+.. _pyporting-howto:
+
+*********************************
+Porting Python 2 Code to Python 3
+*********************************
+
+:author: Brett Cannon
+
+.. topic:: Abstract
+
+ With Python 3 being the future of Python while Python 2 is still in active
+ use, it is good to have your project available for both major releases of
+ Python. This guide is meant to help you choose which strategy works best
+ for your project to support both Python 2 & 3 along with how to execute
+ that strategy.
+
+ If you are looking to port an extension module instead of pure Python code,
+ please see :ref:`cporting-howto`.
+
+
+Choosing a Strategy
+===================
+
+When a project makes the decision that it's time to support both Python 2 & 3,
+a decision needs to be made as to how to go about accomplishing that goal.
+The chosen strategy will depend on how large the project's existing
+codebase is and how much divergence you want from your Python 2 codebase from
+your Python 3 one (e.g., starting a new version with Python 3).
+
+If your project is brand-new or does not have a large codebase, then you may
+want to consider writing/porting :ref:`all of your code for Python 3
+and use 3to2 <use_3to2>` to port your code for Python 2.
+
+If you would prefer to maintain a codebase which is semantically **and**
+syntactically compatible with Python 2 & 3 simultaneously, you can write
+:ref:`use_same_source`. While this tends to lead to somewhat non-idiomatic
+code, it does mean you keep a rapid development process for you, the developer.
+
+Finally, you do have the option of :ref:`using 2to3 <use_2to3>` to translate
+Python 2 code into Python 3 code (with some manual help). This can take the
+form of branching your code and using 2to3 to start a Python 3 branch. You can
+also have users perform the translation as installation time automatically so
+that you only have to maintain a Python 2 codebase.
+
+Regardless of which approach you choose, porting is not as hard or
+time-consuming as you might initially think. You can also tackle the problem
+piece-meal as a good portion of porting is simply updating your code to follow
+current best practices in a Python 2/3 compatible way.
+
+
+Universal Bits of Advice
+------------------------
+
+Regardless of what strategy you pick, there are a few things you should
+consider.
+
+One is 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 version of Python.
+This means making sure your test suite is thorough and is ported properly
+between Python 2 & 3. You will also most likely want to use something like tox_
+to automate testing between both a Python 2 and Python 3 VM.
+
+Two, once your project has Python 3 support, make sure to add the proper
+classifier on the Cheeseshop_ (PyPI_). To have your project listed as Python 3
+compatible it must have the
+`Python 3 classifier <http://pypi.python.org/pypi?:action=browse&c=533>`_
+(from
+http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/)::
+
+ setup(
+ name='Your Library',
+ version='1.0',
+ classifiers=[
+ # make sure to use :: Python *and* :: Python :: 3 so
+ # that pypi can list the package on the python 3 page
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 3'
+ ],
+ packages=['yourlibrary'],
+ # make sure to add custom_fixers to the MANIFEST.in
+ include_package_data=True,
+ # ...
+ )
+
+
+Doing so will cause your project to show up in the
+`Python 3 packages list
+<http://pypi.python.org/pypi?:action=browse&c=533&show=all>`_. You will know
+you set the classifier properly as visiting your project page on the Cheeseshop
+will show a Python 3 logo in the upper-left corner of the page.
+
+Three, the six_ project provides a library which helps iron out differences
+between Python 2 & 3. If you find there is a sticky point that is a continual
+point of contention in your translation or maintenance of code, consider using
+a source-compatible solution relying on six. If you have to create your own
+Python 2/3 compatible solution, you can use ``sys.version_info[0] >= 3`` as a
+guard.
+
+Four, read all the approaches. Just because some bit of advice applies to one
+approach more than another doesn't mean that some advice doesn't apply to other
+strategies.
+
+Five, 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. So choose the newest version
+of Python which you believe can be your minimum support version
+and work from there.
+
+
+.. _tox: http://codespeak.net/tox/
+.. _Cheeseshop:
+.. _PyPI: http://pypi.python.org/
+.. _six: http://packages.python.org/six
+.. _Python 2.7: http://www.python.org/2.7.x
+.. _Python 2.6: http://www.python.org/2.6.x
+.. _Python 2.5: http://www.python.org/2.5.x
+.. _Python 2.4: http://www.python.org/2.4.x
+.. _Python 2.3: http://www.python.org/2.3.x
+.. _Python 2.2: http://www.python.org/2.2.x
+
+
+.. _use_3to2:
+
+Python 3 and 3to2
+=================
+
+If you are starting a new project or your codebase is small enough, you may
+want to consider writing your code for Python 3 and backporting to Python 2
+using 3to2_. Thanks to Python 3 being more strict about things than Python 2
+(e.g., bytes vs. strings), the source translation can be easier and more
+straightforward than from Python 2 to 3. Plus it gives you more direct
+experience developing in Python 3 which, since it is the future of Python, is a
+good thing long-term.
+
+A drawback of this approach is that 3to2 is a third-party project. This means
+that the Python core developers (and thus this guide) can make no promises
+about how well 3to2 works at any time. There is nothing to suggest, though,
+that 3to2 is not a high-quality project.
+
+
+.. _3to2: https://bitbucket.org/amentajo/lib3to2/overview
+
+
+.. _use_2to3:
+
+Python 2 and 2to3
+=================
+
+Included with Python since 2.6, the 2to3_ tool (and :mod:`lib2to3` module)
+helps with porting Python 2 to Python 3 by performing various source
+translations. This is a perfect solution for projects which wish to branch
+their Python 3 code from their Python 2 codebase and maintain them as
+independent codebases. You can even begin preparing to use this approach
+today by writing future-compatible Python code which works cleanly in
+Python 2 in conjunction with 2to3; all steps outlined below will work
+with Python 2 code up to the point when the actual use of 2to3 occurs.
+
+Use of 2to3 as an on-demand translation step at install time is also possible,
+preventing the need to maintain a separate Python 3 codebase, but this approach
+does come with some drawbacks. While users will only have to pay the
+translation cost once at installation, you as a developer will need to pay the
+cost regularly during development. If your codebase is sufficiently large
+enough then the translation step ends up acting like a compilation step,
+robbing you of the rapid development process you are used to with Python.
+Obviously the time required to translate a project will vary, so do an
+experimental translation just to see how long it takes to evaluate whether you
+prefer this approach compared to using :ref:`use_same_source` or simply keeping
+a separate Python 3 codebase.
+
+Below are the typical steps taken by a project which uses a 2to3-based approach
+to supporting Python 2 & 3.
+
+
+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 which 2to3 cannot handle but are
+known to cause issues.
+
+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
+porting to Python 3. But if you project must keep support for `Python 2.5`_ (or
+even `Python 2.4`_) then it is still possible to port to 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.
+
+
+``from __future__ import print_function``
+'''''''''''''''''''''''''''''''''''''''''
+
+This is a personal choice. 2to3 handles the translation from the print
+statement to the print function rather well so this is an optional step. This
+future statement does help, though, with getting used to typing
+``print('Hello, World')`` instead of ``print 'Hello, World'``.
+
+
+``from __future__ import unicode_literals``
+'''''''''''''''''''''''''''''''''''''''''''
+
+Another personal choice. You can always mark what you want to be a (unicode)
+string with a ``u`` prefix to get the same effect. But regardless of whether
+you use this future statement or not, you **must** make sure you know exactly
+which Python 2 strings you want to be bytes, and which are to be strings. This
+means you should, **at minimum** mark all strings that are meant to be text
+strings with a ``u`` prefix if you do not use this future statement.
+
+
+Bytes literals
+''''''''''''''
+
+This is a **very** important one. The ability to prefix Python 2 strings that
+are meant to contain bytes with a ``b`` prefix help to very clearly delineate
+what is and is not a Python 3 string. When you run 2to3 on code, all Python 2
+strings become Python 3 strings **unless** they are prefixed with ``b``.
+
+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.
+Probably the biggest "gotcha" is that indexing results in different values. In
+Python 2, the value of ``b'py'[1]`` is ``'y'``, while in Python 3 it's ``121``.
+You can avoid this disparity by always slicing at the size of a single element:
+``b'py'[1:2]`` is ``'y'`` in Python 2 and ``b'y'`` in Python 3 (i.e., close
+enough).
+
+You cannot concatenate bytes and strings in Python 3. But since in Python
+2 has bytes aliased to ``str``, it will succeed: ``b'a' + u'b'`` works in
+Python 2, but ``b'a' + 'b'`` in Python 3 is a :exc:`TypeError`. A similar issue
+also comes about when doing comparisons between bytes and strings.
+
+
+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``) does 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 the __future__ statement.
+
+
+
+Handle Common "Gotchas"
+-----------------------
+
+There are a few things that just consistently come up as sticking points for
+people which 2to3 cannot handle automatically or can easily be done in Python 2
+to help modernize your code.
+
+
+``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
+'''''''''''''''''''''''''''''''''''''
+
+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
+handling this issue to to make sure that **every** string literal in your
+Python 2 code is either syntactically of 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 pre-dating 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).
+
+There are two ways to solve this issue. One is to use a custom 2to3 fixer. The
+blog post at http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
+specifies how to do this. That will allow 2to3 to change all instances of ``def
+__unicode(self): ...`` to ``def __str__(self): ...``. This does require you
+define your ``__str__()`` method in Python 2 before your ``__unicode__()``
+method.
+
+The other option is to use a mixin class. 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
+'''''''''''''''''
+
+2to3_ will attempt to generate fixes for doctests that it comes across. It's
+not perfect, though. 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`.
+
+
+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 2to3 cannot handle automatically (e.g., modules that have been
+removed). Try to eliminate those warnings to make your code even more portable
+to Python 3.
+
+
+Run 2to3
+--------
+
+Once you have made your Python 2 code future-compatible with Python 3, it's
+time to use 2to3_ to actually port your code.
+
+
+Manually
+''''''''
+
+To manually convert source code using 2to3_, you use the ``2to3`` script that
+is installed with Python 2.6 and later.::
+
+ 2to3 <directory or file to convert>
+
+This will cause 2to3 to write out a diff with all of the fixers applied for the
+converted source code. If you would like 2to3 to go ahead and apply the changes
+you can pass it the ``-w`` flag::
+
+ 2to3 -w <stuff to convert>
+
+There are other flags available to control exactly which fixers are applied,
+etc.
+
+
+During Installation
+'''''''''''''''''''
+
+When a user installs your project for Python 3, you can have either
+:mod:`distutils` or Distribute_ run 2to3_ on your behalf.
+For distutils, use the following idiom::
+
+ try: # Python 3
+ from distutils.command.build_py import build_py_2to3 as build_py
+ except ImportError: # Python 2
+ from distutils.command.build_py import build_py
+
+ setup(cmdclass = {'build_py': build_py},
+ # ...
+ )
+
+For Distribute::
+
+ setup(use_2to3=True,
+ # ...
+ )
+
+This will allow you to not have to distribute a separate Python 3 version of
+your project. It does require, though, that when you perform development that
+you at least build your project and use the built Python 3 source for testing.
+
+
+Verify & Test
+-------------
+
+At this point you should (hopefully) have your project converted in such a way
+that it works in Python 3. Verify it by running your unit tests and making sure
+nothing has gone awry. If you miss something then figure out how to fix it in
+Python 3, backport to your Python 2 code, and run your code through 2to3 again
+to verify the fix transforms properly.
+
+
+.. _2to3: http://docs.python.org/py3k/library/2to3.html
+.. _Distribute: http://packages.python.org/distribute/
+
+
+.. _use_same_source:
+
+Python 2/3 Compatible Source
+============================
+
+While it may seem counter-intuitive, you can write Python code which is
+source-compatible between Python 2 & 3. It does lead to code that is not
+entirely idiomatic Python (e.g., having to extract the currently raised
+exception from ``sys.exc_info()[1]``), but it can be run under Python 2
+**and** Python 3 without using 2to3_ as a translation step (although the tool
+should be used to help find potential portability problems). This allows you to
+continue to have a rapid development process regardless of whether you are
+developing under Python 2 or Python 3. Whether this approach or using
+:ref:`use_2to3` works best for you will be a per-project decision.
+
+To get a complete idea of what issues you will need to deal with, see the
+`What's New in Python 3.0`_. Others have reorganized the data in other formats
+such as http://docs.pythonsprints.com/python3_porting/py-porting.html .
+
+The following are some steps to take to try to support both Python 2 & 3 from
+the same source code.
+
+
+.. _What's New in Python 3.0: http://docs.python.org/release/3.0/whatsnew/3.0.html
+
+
+Follow The Steps for Using 2to3_
+--------------------------------
+
+All of the steps outlined in how to
+:ref:`port Python 2 code with 2to3 <use_2to3>` apply
+to creating a Python 2/3 codebase. This includes trying only support Python 2.6
+or newer (the :mod:`__future__` statements work in Python 3 without issue),
+eliminating warnings that are triggered by ``-3``, etc.
+
+You should even consider running 2to3_ over your code (without committing the
+changes). This will let you know where potential pain points are within your
+code so that you can fix them properly before they become an issue.
+
+
+Use six_
+--------
+
+The six_ project contains many things to help you write portable Python code.
+You should make sure to read its documentation from beginning to end and use
+any and all features it provides. That way you will minimize any mistakes you
+might make in writing cross-version code.
+
+
+Capturing the Currently Raised Exception
+----------------------------------------
+
+One change between Python 2 and 3 that will require changing how you code (if
+you support `Python 2.5`_ and earlier) is
+accessing 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; Python 2.6 will "leak"
+ pass
+
+Because of this syntax change you must change to capturing the current
+exception 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.
+
+
+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):
+
+* 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/
+* http://wiki.python.org/moin/PortingPythonToPy3k
+
+If you feel there is something missing from this document that should be added,
+please email the python-porting_ mailing list.
+
+.. _python-porting: http://mail.python.org/mailman/listinfo/python-porting
diff --git a/Doc/howto/sockets.rst b/Doc/howto/sockets.rst
index 4002a3d..b0a3fa4 100644
--- a/Doc/howto/sockets.rst
+++ b/Doc/howto/sockets.rst
@@ -43,10 +43,10 @@
History
-------
-Of the various forms of IPC (*Inter Process Communication*), sockets are by far
-the most popular. On any given platform, there are likely to be other forms of
-IPC that are faster, but for cross-platform communication, sockets are about the
-only game in town.
+Of the various forms of :abbr:`IPC (Inter Process Communication)`,
+sockets are by far the most popular. On any given platform, there are
+likely to be other forms of IPC that are faster, but for
+cross-platform communication, sockets are about the only game in town.
They were invented in Berkeley as part of the BSD flavor of Unix. They spread
like wildfire with the Internet. With good reason --- the combination of sockets
@@ -67,13 +67,14 @@
# - the normal http port
s.connect(("www.mcmillan-inc.com", 80))
-When the ``connect`` completes, the socket ``s`` can now be used to send in a
-request for the text of this page. The same socket will read the reply, and then
-be destroyed. That's right - destroyed. Client sockets are normally only used
-for one exchange (or a small set of sequential exchanges).
+When the ``connect`` completes, the socket ``s`` can be used to send
+in a request for the text of the page. The same socket will read the
+reply, and then be destroyed. That's right, destroyed. Client sockets
+are normally only used for one exchange (or a small set of sequential
+exchanges).
What happens in the web server is a bit more complex. First, the web server
-creates a "server socket". ::
+creates a "server socket"::
#create an INET, STREAMing socket
serversocket = socket.socket(
@@ -97,7 +98,7 @@
queue up as many as 5 connect requests (the normal max) before refusing outside
connections. If the rest of the code is written properly, that should be plenty.
-OK, now we have a "server" socket, listening on port 80. Now we enter the
+Now that we have a "server" socket, listening on port 80, we can enter the
mainloop of the web server::
while 1:
@@ -146,7 +147,7 @@
Now there are two sets of verbs to use for communication. You can use ``send``
and ``recv``, or you can transform your client socket into a file-like beast and
-use ``read`` and ``write``. The latter is the way Java presents their sockets.
+use ``read`` and ``write``. The latter is the way Java presents its sockets.
I'm not going to talk about it here, except to warn you that you need to use
``flush`` on sockets. These are buffered "files", and a common mistake is to
``write`` something, and then ``read`` for a reply. Without a ``flush`` in
@@ -167,11 +168,11 @@
about that some on the next page.
A protocol like HTTP uses a socket for only one transfer. The client sends a
-request, the reads a reply. That's it. The socket is discarded. This means that
+request, then reads a reply. That's it. The socket is discarded. This means that
a client can detect the end of the reply by receiving 0 bytes.
But if you plan to reuse your socket for further transfers, you need to realize
-that *there is no "EOT" (End of Transfer) on a socket.* I repeat: if a socket
+that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket
``send`` or ``recv`` returns after handling 0 bytes, the connection has been
broken. If the connection has *not* been broken, you may wait on a ``recv``
forever, because the socket will *not* tell you that there's nothing more to
@@ -337,7 +338,7 @@
In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but
it's close enough to the C version that if you understand ``select`` in Python,
-you'll have little trouble with it in C. ::
+you'll have little trouble with it in C::
ready_to_read, ready_to_write, in_error = \
select.select(
@@ -354,10 +355,9 @@
thing to do - give it a nice long timeout (say a minute) unless you have good
reason to do otherwise.
-In return, you will get three lists. They have the sockets that are actually
+In return, you will get three lists. They contain the sockets that are actually
readable, writable and in error. Each of these lists is a subset (possibly
-empty) of the corresponding list you passed in. And if you put a socket in more
-than one input list, it will only be (at most) in one output list.
+empty) of the corresponding list you passed in.
If a socket is in the output readable list, you can be
as-close-to-certain-as-we-ever-get-in-this-business that a ``recv`` on that
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst
index 746e40c..acdf3ab 100644
--- a/Doc/howto/sorting.rst
+++ b/Doc/howto/sorting.rst
@@ -111,6 +111,15 @@
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
+The :func:`operator.methodcaller` function makes method calls with fixed
+parameters for each object being sorted. For example, the :meth:`str.count`
+method could be used to compute message priority by counting the
+number of exclamation marks in a message:
+
+ >>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
+ >>> sorted(messages, key=methodcaller('count', '!'))
+ ['standby', 'hurry!', 'immediate!!', 'critical!!!']
+
Ascending and Descending
========================
@@ -259,8 +268,8 @@
* For locale aware sorting, use :func:`locale.strxfrm` for a key function or
:func:`locale.strcoll` for a comparison function.
-* The *reverse* parameter still maintains sort stability (i.e. records with
- equal keys retain the original order). Interestingly, that effect can be
+* The *reverse* parameter still maintains sort stability (so that records with
+ equal keys retain their original order). Interestingly, that effect can be
simulated without the parameter by using the builtin :func:`reversed` function
twice:
@@ -275,12 +284,16 @@
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
+ For general purpose comparisons, the recommended approach is to define all six
+ rich comparison operators. The :func:`functools.total_ordering` class
+ decorator makes this easy to implement.
+
* Key functions need not depend directly on the objects being sorted. A key
function can also access external resources. For instance, if the student grades
are stored in a dictionary, they can be used to sort a separate list of student
names:
>>> students = ['dave', 'john', 'jane']
- >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
- >>> sorted(students, key=newgrades.__getitem__)
+ >>> grades = {'john': 'F', 'jane':'A', 'dave': 'C'}
+ >>> sorted(students, key=grades.__getitem__)
['jane', 'dave', 'john']
diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst
index e10a5a4..6c80c77 100644
--- a/Doc/howto/urllib2.rst
+++ b/Doc/howto/urllib2.rst
@@ -138,7 +138,7 @@
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
- >>> data = urllib2.open(full_url)
+ >>> data = urllib2.urlopen(full_url)
Notice that the full URL is created by adding a ``?`` to the URL, followed by
the encoded values.
diff --git a/Doc/includes/capsulethunk.h b/Doc/includes/capsulethunk.h
new file mode 100644
index 0000000..6b20564
--- /dev/null
+++ b/Doc/includes/capsulethunk.h
@@ -0,0 +1,134 @@
+#ifndef __CAPSULETHUNK_H
+#define __CAPSULETHUNK_H
+
+#if ( (PY_VERSION_HEX < 0x02070000) \
+ || ((PY_VERSION_HEX >= 0x03000000) \
+ && (PY_VERSION_HEX < 0x03010000)) )
+
+#define __PyCapsule_GetField(capsule, field, default_value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field) \
+ : (default_value) \
+ ) \
+
+#define __PyCapsule_SetField(capsule, field, value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field = value), 1 \
+ : 0 \
+ ) \
+
+
+#define PyCapsule_Type PyCObject_Type
+
+#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
+#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
+
+
+#define PyCapsule_New(pointer, name, destructor) \
+ (PyCObject_FromVoidPtr(pointer, destructor))
+
+
+#define PyCapsule_GetPointer(capsule, name) \
+ (PyCObject_AsVoidPtr(capsule))
+
+/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
+#define PyCapsule_SetPointer(capsule, pointer) \
+ __PyCapsule_SetField(capsule, cobject, pointer)
+
+
+#define PyCapsule_GetDestructor(capsule) \
+ __PyCapsule_GetField(capsule, destructor)
+
+#define PyCapsule_SetDestructor(capsule, dtor) \
+ __PyCapsule_SetField(capsule, destructor, dtor)
+
+
+/*
+ * Sorry, there's simply no place
+ * to store a Capsule "name" in a CObject.
+ */
+#define PyCapsule_GetName(capsule) NULL
+
+static int
+PyCapsule_SetName(PyObject *capsule, const char *unused)
+{
+ unused = unused;
+ PyErr_SetString(PyExc_NotImplementedError,
+ "can't use PyCapsule_SetName with CObjects");
+ return 1;
+}
+
+
+
+#define PyCapsule_GetContext(capsule) \
+ __PyCapsule_GetField(capsule, descr)
+
+#define PyCapsule_SetContext(capsule, context) \
+ __PyCapsule_SetField(capsule, descr, context)
+
+
+static void *
+PyCapsule_Import(const char *name, int no_block)
+{
+ PyObject *object = NULL;
+ void *return_value = NULL;
+ char *trace;
+ size_t name_length = (strlen(name) + 1) * sizeof(char);
+ char *name_dup = (char *)PyMem_MALLOC(name_length);
+
+ if (!name_dup) {
+ return NULL;
+ }
+
+ memcpy(name_dup, name, name_length);
+
+ trace = name_dup;
+ while (trace) {
+ char *dot = strchr(trace, '.');
+ if (dot) {
+ *dot++ = '\0';
+ }
+
+ if (object == NULL) {
+ if (no_block) {
+ object = PyImport_ImportModuleNoBlock(trace);
+ } else {
+ object = PyImport_ImportModule(trace);
+ if (!object) {
+ PyErr_Format(PyExc_ImportError,
+ "PyCapsule_Import could not "
+ "import module \"%s\"", trace);
+ }
+ }
+ } else {
+ PyObject *object2 = PyObject_GetAttrString(object, trace);
+ Py_DECREF(object);
+ object = object2;
+ }
+ if (!object) {
+ goto EXIT;
+ }
+
+ trace = dot;
+ }
+
+ if (PyCObject_Check(object)) {
+ PyCObject *cobject = (PyCObject *)object;
+ return_value = cobject->cobject;
+ } else {
+ PyErr_Format(PyExc_AttributeError,
+ "PyCapsule_Import \"%s\" is not valid",
+ name);
+ }
+
+EXIT:
+ Py_XDECREF(object);
+ if (name_dup) {
+ PyMem_FREE(name_dup);
+ }
+ return return_value;
+}
+
+#endif /* #if PY_VERSION_HEX < 0x02070000 */
+
+#endif /* __CAPSULETHUNK_H */
diff --git a/Doc/includes/email-dir.py b/Doc/includes/email-dir.py
index e67de61..035442b 100644
--- a/Doc/includes/email-dir.py
+++ b/Doc/includes/email-dir.py
@@ -105,7 +105,7 @@
fp.write(composed)
fp.close()
else:
- s = smtplib.SMTP()
+ s = smtplib.SMTP('localhost')
s.sendmail(opts.sender, opts.recipients, composed)
s.quit()
diff --git a/Doc/includes/email-mime.py b/Doc/includes/email-mime.py
index f64df83..7b1c028 100644
--- a/Doc/includes/email-mime.py
+++ b/Doc/includes/email-mime.py
@@ -26,6 +26,6 @@
msg.attach(img)
# Send the email via our own SMTP server.
-s = smtplib.SMTP()
+s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()
diff --git a/Doc/includes/email-simple.py b/Doc/includes/email-simple.py
index 689511e..29bd078 100644
--- a/Doc/includes/email-simple.py
+++ b/Doc/includes/email-simple.py
@@ -19,6 +19,6 @@
# Send the message via our own SMTP server, but don't include the
# envelope header.
-s = smtplib.SMTP()
+s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
diff --git a/Doc/install/index.rst b/Doc/install/index.rst
index af113ee..abce88d 100644
--- a/Doc/install/index.rst
+++ b/Doc/install/index.rst
@@ -72,7 +72,7 @@
do the obvious thing with it: run it if it's an executable installer, ``rpm
--install`` it if it's an RPM, etc. You don't need to run Python or a setup
script, you don't need to compile anything---you might not even need to read any
-instructions (although it's always a good idea to do so anyways).
+instructions (although it's always a good idea to do so anyway).
Of course, things will not always be that easy. You might be interested in a
module distribution that doesn't have an easy-to-use installer for your
@@ -96,10 +96,16 @@
directory: :file:`foo-1.0` or :file:`widget-0.9.7`. Additionally, the
distribution will contain a setup script :file:`setup.py`, and a file named
:file:`README.txt` or possibly just :file:`README`, which should explain that
-building and installing the module distribution is a simple matter of running ::
+building and installing the module distribution is a simple matter of running
+one command from a terminal::
python setup.py install
+For Windows, this command should be run from a command prompt window
+(:menuselection:`Start --> Accessories`)::
+
+ setup.py install
+
If all these things are true, then you already know how to build and install the
modules you've just downloaded: Run the command above. Unless you need to
install things in a non-standard way or customize the build process, you don't
@@ -113,14 +119,11 @@
==========================
As described in section :ref:`inst-new-standard`, building and installing a module
-distribution using the Distutils is usually one simple command::
+distribution using the Distutils is usually one simple command to run from a
+terminal::
python setup.py install
-On Unix, you'd run this command from a shell prompt; on Windows, you have to
-open a command prompt window ("DOS box") and do it there; on Mac OS X, you open
-a :command:`Terminal` window to get a shell prompt.
-
.. _inst-platform-variations:
@@ -141,7 +144,7 @@
:file:`C:\\Temp\\foo-1.0`; you can use either a archive manipulator with a
graphical user interface (such as WinZip) or a command-line tool (such as
:program:`unzip` or :program:`pkunzip`) to unpack the archive. Then, open a
-command prompt window ("DOS box"), and run::
+command prompt window and run::
cd c:\Temp\foo-1.0
python setup.py install
@@ -241,7 +244,7 @@
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
| Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) |
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
-| Windows | :file:`{prefix}` | :file:`C:\\Python` | \(2) |
+| Windows | :file:`{prefix}\\Lib\\site-packages` | :file:`C:\\Python{XY}\\Lib\\site-packages` | \(2) |
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
Notes:
@@ -276,6 +279,12 @@
>>> sys.exec_prefix
'/usr'
+A few other placeholders are used in this document: :file:`{X.Y}` stands for the
+version of Python, for example ``2.7``; :file:`{distname}` will be replaced by
+the name of the module distribution being installed. Dots and capitalization
+are important in the paths; for example, a value that uses ``python2.7`` on UNIX
+will typically use ``Python27`` on Windows.
+
If you don't want to install modules to the standard location, or if you don't
have permission to write there, then you need to read about alternate
installations in section :ref:`inst-alt-install`. If you want to customize your
@@ -304,8 +313,61 @@
differ across platforms, so read whichever of the following sections applies to
you.
+Note that the various alternate installation schemes are mutually exclusive: you
+can pass ``--user``, or ``--home``, or ``--prefix`` and ``--exec-prefix``, or
+``--install-base`` and ``--install-platbase``, but you can't mix from these
+groups.
-.. _inst-alt-install-prefix:
+
+.. _inst-alt-install-user:
+
+Alternate installation: the user scheme
+---------------------------------------
+
+This scheme is designed to be the most convenient solution for users that don't
+have write permission to the global site-packages directory or don't want to
+install into it. It is enabled with a simple option::
+
+ python setup.py install --user
+
+Files will be installed into subdirectories of :data:`site.USER_BASE` (written
+as :file:`{userbase}` hereafter). This scheme installs pure Python modules and
+extension modules in the same location (also known as :data:`site.USER_SITE`).
+Here are the values for UNIX, including Mac OS X:
+
+=============== ===========================================================
+Type of file Installation directory
+=============== ===========================================================
+modules :file:`{userbase}/lib/python{X.Y}/site-packages`
+scripts :file:`{userbase}/bin`
+data :file:`{userbase}`
+C headers :file:`{userbase}/include/python{X.Y}/{distname}`
+=============== ===========================================================
+
+And here are the values used on Windows:
+
+=============== ===========================================================
+Type of file Installation directory
+=============== ===========================================================
+modules :file:`{userbase}\\Python{XY}\\site-packages`
+scripts :file:`{userbase}\\Scripts`
+data :file:`{userbase}`
+C headers :file:`{userbase}\\Python{XY}\\Include\\{distname}`
+=============== ===========================================================
+
+The advantage of using this scheme compared to the other ones described below is
+that the user site-packages directory is under normal conditions always included
+in :data:`sys.path` (see :mod:`site` for more information), which means that
+there is no additional step to perform after running the :file:`setup.py` script
+to finalize the installation.
+
+The :command:`build_ext` command also has a ``--user`` option to add
+:file:`{userbase}/include` to the compiler search path for header files and
+:file:`{userbase}/lib` to the compiler search path for libraries as well as to
+the runtime search path for shared C libraries (rpath).
+
+
+.. _inst-alt-install-home:
Alternate installation: the home scheme
---------------------------------------
@@ -327,26 +389,30 @@
python setup.py install --home=~
+To make Python find the distributions installed with this scheme, you may have
+to :ref:`modify Python's search path <inst-search-path>` or edit
+:mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit
+:data:`sys.path`.
+
The :option:`--home` option defines the installation base directory. Files are
installed to the following directories under the installation base as follows:
-+------------------------------+---------------------------+-----------------------------+
-| Type of file | Installation Directory | Override option |
-+==============================+===========================+=============================+
-| pure module distribution | :file:`{home}/lib/python` | :option:`--install-purelib` |
-+------------------------------+---------------------------+-----------------------------+
-| non-pure module distribution | :file:`{home}/lib/python` | :option:`--install-platlib` |
-+------------------------------+---------------------------+-----------------------------+
-| scripts | :file:`{home}/bin` | :option:`--install-scripts` |
-+------------------------------+---------------------------+-----------------------------+
-| data | :file:`{home}/share` | :option:`--install-data` |
-+------------------------------+---------------------------+-----------------------------+
+=============== ===========================================================
+Type of file Installation directory
+=============== ===========================================================
+modules :file:`{home}/lib/python`
+scripts :file:`{home}/bin`
+data :file:`{home}`
+C headers :file:`{home}/include/python/{distname}`
+=============== ===========================================================
+
+(Mentally replace slashes with backslashes if you're on Windows.)
.. versionchanged:: 2.4
The :option:`--home` option used to be supported only on Unix.
-.. _inst-alt-install-home:
+.. _inst-alt-install-prefix-unix:
Alternate installation: Unix (the prefix scheme)
------------------------------------------------
@@ -355,7 +421,7 @@
perform the build/install (i.e., to run the setup script), but install modules
into the third-party module directory of a different Python installation (or
something that looks like a different Python installation). If this sounds a
-trifle unusual, it is---that's why the "home scheme" comes first. However,
+trifle unusual, it is---that's why the user and home schemes come before. However,
there are at least two known cases where the prefix scheme will be useful.
First, consider that many Linux distributions put Python in :file:`/usr`, rather
@@ -383,17 +449,15 @@
executables, etc.) If :option:`--exec-prefix` is not supplied, it defaults to
:option:`--prefix`. Files are installed as follows:
-+------------------------------+-----------------------------------------------------+-----------------------------+
-| Type of file | Installation Directory | Override option |
-+==============================+=====================================================+=============================+
-| pure module distribution | :file:`{prefix}/lib/python{X.Y}/site-packages` | :option:`--install-purelib` |
-+------------------------------+-----------------------------------------------------+-----------------------------+
-| non-pure module distribution | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :option:`--install-platlib` |
-+------------------------------+-----------------------------------------------------+-----------------------------+
-| scripts | :file:`{prefix}/bin` | :option:`--install-scripts` |
-+------------------------------+-----------------------------------------------------+-----------------------------+
-| data | :file:`{prefix}/share` | :option:`--install-data` |
-+------------------------------+-----------------------------------------------------+-----------------------------+
+================= ==========================================================
+Type of file Installation directory
+================= ==========================================================
+Python modules :file:`{prefix}/lib/python{X.Y}/site-packages`
+extension modules :file:`{exec-prefix}/lib/python{X.Y}/site-packages`
+scripts :file:`{prefix}/bin`
+data :file:`{prefix}`
+C headers :file:`{prefix}/include/python{X.Y}/{distname}`
+================= ==========================================================
There is no requirement that :option:`--prefix` or :option:`--exec-prefix`
actually point to an alternate Python installation; if the directories listed
@@ -418,7 +482,7 @@
alternate Python installation, this is immaterial.)
-.. _inst-alt-install-windows:
+.. _inst-alt-install-prefix-windows:
Alternate installation: Windows (the prefix scheme)
---------------------------------------------------
@@ -433,20 +497,18 @@
to install modules to the :file:`\\Temp\\Python` directory on the current drive.
The installation base is defined by the :option:`--prefix` option; the
-:option:`--exec-prefix` option is not supported under Windows. Files are
-installed as follows:
+:option:`--exec-prefix` option is not supported under Windows, which means that
+pure Python modules and extension modules are installed into the same location.
+Files are installed as follows:
-+------------------------------+---------------------------+-----------------------------+
-| Type of file | Installation Directory | Override option |
-+==============================+===========================+=============================+
-| pure module distribution | :file:`{prefix}` | :option:`--install-purelib` |
-+------------------------------+---------------------------+-----------------------------+
-| non-pure module distribution | :file:`{prefix}` | :option:`--install-platlib` |
-+------------------------------+---------------------------+-----------------------------+
-| scripts | :file:`{prefix}\\Scripts` | :option:`--install-scripts` |
-+------------------------------+---------------------------+-----------------------------+
-| data | :file:`{prefix}\\Data` | :option:`--install-data` |
-+------------------------------+---------------------------+-----------------------------+
+=============== ==========================================================
+Type of file Installation directory
+=============== ==========================================================
+modules :file:`{prefix}\\Lib\\site-packages`
+scripts :file:`{prefix}\\Scripts`
+data :file:`{prefix}`
+C headers :file:`{prefix}\\Include\\{distname}`
+=============== ==========================================================
.. _inst-custom-install:
@@ -460,13 +522,29 @@
or you might want to completely redefine the installation scheme. In either
case, you're creating a *custom installation scheme*.
-You probably noticed the column of "override options" in the tables describing
-the alternate installation schemes above. Those options are how you define a
-custom installation scheme. These override options can be relative, absolute,
+To create a custom installation scheme, you start with one of the alternate
+schemes and override some of the installation directories used for the various
+types of files, using these options:
+
+====================== =======================
+Type of file Override option
+====================== =======================
+Python modules ``--install-purelib``
+extension modules ``--install-platlib``
+all modules ``--install-lib``
+scripts ``--install-scripts``
+data ``--install-data``
+C headers ``--install-headers``
+====================== =======================
+
+These override options can be relative, absolute,
or explicitly defined in terms of one of the installation base directories.
(There are two installation base directories, and they are normally the same---
they only differ when you use the Unix "prefix scheme" and supply different
-:option:`--prefix` and :option:`--exec-prefix` options.)
+``--prefix`` and ``--exec-prefix`` options; using ``--install-lib`` will
+override values computed or given for ``--install-purelib`` and
+``--install-platlib``, and is recommended for schemes that don't make a
+difference between Python and extension modules.)
For example, say you're installing a module distribution to your home directory
under Unix---but you want scripts to go in :file:`~/scripts` rather than
@@ -493,15 +571,16 @@
a subdirectory of :file:`{prefix}`, rather than right in :file:`{prefix}`
itself. This is almost as easy as customizing the script installation directory
---you just have to remember that there are two types of modules to worry about,
-pure modules and non-pure modules (i.e., modules from a non-pure distribution).
-For example::
+Python and extension modules, which can conveniently be both controlled by one
+option::
- python setup.py install --install-purelib=Site --install-platlib=Site
+ python setup.py install --install-lib=Site
-The specified installation directories are relative to :file:`{prefix}`. Of
-course, you also have to ensure that these directories are in Python's module
-search path, such as by putting a :file:`.pth` file in :file:`{prefix}`. See
-section :ref:`inst-search-path` to find out how to modify Python's search path.
+The specified installation directory is relative to :file:`{prefix}`. Of
+course, you also have to ensure that this directory is in Python's module
+search path, such as by putting a :file:`.pth` file in a site directory (see
+:mod:`site`). See section :ref:`inst-search-path` to find out how to modify
+Python's search path.
If you want to define an entire installation scheme, you just have to supply all
of the installation directory options. The recommended way to do this is to
@@ -553,8 +632,8 @@
python setup.py install --install-base=/tmp
-would install pure modules to :file:`{/tmp/python/lib}` in the first case, and
-to :file:`{/tmp/lib}` in the second case. (For the second case, you probably
+would install pure modules to :file:`/tmp/python/lib` in the first case, and
+to :file:`/tmp/lib` in the second case. (For the second case, you probably
want to supply an installation base of :file:`/tmp/python`.)
You probably noticed the use of ``$HOME`` and ``$PLAT`` in the sample
@@ -571,7 +650,7 @@
needed on those platforms?
-.. XXX I'm not sure where this section should go.
+.. XXX Move this to Doc/using
.. _inst-search-path:
diff --git a/Doc/library/2to3.rst b/Doc/library/2to3.rst
index de31251..555675c 100644
--- a/Doc/library/2to3.rst
+++ b/Doc/library/2to3.rst
@@ -230,7 +230,7 @@
.. 2to3fixer:: long
- Strips the ``L`` prefix on long literals and renames :class:`long` to
+ Strips the ``L`` suffix on long literals and renames :class:`long` to
:class:`int`.
.. 2to3fixer:: map
diff --git a/Doc/library/__builtin__.rst b/Doc/library/__builtin__.rst
index ec189b6..673d74f 100644
--- a/Doc/library/__builtin__.rst
+++ b/Doc/library/__builtin__.rst
@@ -8,7 +8,9 @@
This module provides direct access to all 'built-in' identifiers of Python; for
example, ``__builtin__.open`` is the full name for the built-in function
-:func:`open`.
+:func:`open`. See :ref:`built-in-funcs` and :ref:`built-in-consts` for
+documentation.
+
This module is not normally accessed explicitly by most applications, but can be
useful in modules that provide objects with the same name as a built-in value,
diff --git a/Doc/library/__future__.rst b/Doc/library/__future__.rst
index 8945c5d..87e1205 100644
--- a/Doc/library/__future__.rst
+++ b/Doc/library/__future__.rst
@@ -4,6 +4,9 @@
.. module:: __future__
:synopsis: Future statement definitions
+**Source code:** :source:`Lib/__future__.py`
+
+--------------
:mod:`__future__` is a real module, and serves three purposes:
diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst
index 9f70b02..ef8b08e 100644
--- a/Doc/library/abc.rst
+++ b/Doc/library/abc.rst
@@ -9,8 +9,12 @@
.. versionadded:: 2.6
-This module provides the infrastructure for defining an :term:`abstract base
-class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
+**Source code:** :source:`Lib/abc.py`
+
+--------------
+
+This module provides the infrastructure for defining :term:`abstract base
+classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
regarding a type hierarchy for numbers based on ABCs.)
diff --git a/Doc/library/aifc.rst b/Doc/library/aifc.rst
index 0bb1635..1265423 100644
--- a/Doc/library/aifc.rst
+++ b/Doc/library/aifc.rst
@@ -10,6 +10,10 @@
single: AIFF
single: AIFF-C
+**Source code:** :source:`Lib/aifc.py`
+
+--------------
+
This module provides support for reading and writing AIFF and AIFF-C files.
AIFF is Audio Interchange File Format, a format for storing digital audio
samples in a file. AIFF-C is a newer version of the format that includes the
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
index 4df5501..09f97a9 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -2,11 +2,15 @@
===============================================================================
.. module:: argparse
- :synopsis: Command-line option and argument-parsing library.
+ :synopsis: Command-line option and argument parsing library.
.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
-.. versionadded:: 2.7
.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
+.. versionadded:: 2.7
+
+**Source code:** :source:`Lib/argparse.py`
+
+--------------
The :mod:`argparse` module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and :mod:`argparse`
@@ -103,10 +107,10 @@
Parsing arguments
^^^^^^^^^^^^^^^^^
-:class:`ArgumentParser` parses args through the
+:class:`ArgumentParser` parses arguments through the
:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
-convert each arg to the appropriate type and then invoke the appropriate action.
-In most cases, this means a simple namespace object will be built up from
+convert each argument to the appropriate type and then invoke the appropriate action.
+In most cases, this means a simple :class:`Namespace` object will be built up from
attributes parsed out of the command line::
>>> parser.parse_args(['--sum', '7', '-1', '42'])
@@ -114,7 +118,7 @@
In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
arguments, and the :class:`ArgumentParser` will automatically determine the
-command-line args from :data:`sys.argv`.
+command-line arguments from :data:`sys.argv`.
ArgumentParser objects
@@ -149,7 +153,7 @@
conflicting optionals.
* prog_ - The name of the program (default:
- :data:`sys.argv[0]`)
+ ``sys.argv[0]``)
* usage_ - The string describing the program usage (default: generated)
@@ -238,7 +242,7 @@
--foo FOO foo help
The help option is typically ``-h/--help``. The exception to this is
-if the ``prefix_chars=`` is specified and does not include ``'-'``, in
+if the ``prefix_chars=`` is specified and does not include ``-``, in
which case ``-h`` and ``--help`` are not valid options. In
this case, the first character in ``prefix_chars`` is used to prefix
the help options::
@@ -254,7 +258,7 @@
prefix_chars
^^^^^^^^^^^^
-Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
+Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
Parsers that need to support different or additional prefix
characters, e.g. for options
like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
@@ -267,7 +271,7 @@
Namespace(bar='Y', f='X')
The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
-characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
+characters that does not include ``-`` will cause ``-f/--foo`` options to be
disallowed.
@@ -389,7 +393,7 @@
likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
-Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
+Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
indicates that description_ and epilog_ are already correctly formatted and
should not be line-wrapped::
@@ -415,7 +419,7 @@
optional arguments:
-h, --help show this help message and exit
-:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
+:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
including argument descriptions.
The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
@@ -642,11 +646,11 @@
action
^^^^^^
-:class:`ArgumentParser` objects associate command-line args with actions. These
-actions can do just about anything with the command-line args associated with
+:class:`ArgumentParser` objects associate command-line arguments with actions. These
+actions can do just about anything with the command-line arguments associated with
them, though most actions simply add an attribute to the object returned by
:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
-how the command-line args should be handled. The supported actions are:
+how the command-line arguments should be handled. The supported actions are:
* ``'store'`` - This just stores the argument's value. This is the default
action. For example::
@@ -714,12 +718,12 @@
* ``parser`` - The ArgumentParser object which contains this action.
-* ``namespace`` - The namespace object that will be returned by
+* ``namespace`` - The :class:`Namespace` object that will be returned by
:meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
object.
-* ``values`` - The associated command-line args, with any type-conversions
- applied. (Type-conversions are specified with the type_ keyword argument to
+* ``values`` - The associated command-line arguments, with any type conversions
+ applied. (Type conversions are specified with the type_ keyword argument to
:meth:`~ArgumentParser.add_argument`.
* ``option_string`` - The option string that was used to invoke this action.
@@ -751,7 +755,7 @@
different number of command-line arguments with a single action. The supported
values are:
-* N (an integer). N args from the command line will be gathered together into a
+* ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a
list. For example::
>>> parser = argparse.ArgumentParser()
@@ -763,11 +767,11 @@
Note that ``nargs=1`` produces a list of one item. This is different from
the default, in which the item is produced by itself.
-* ``'?'``. One arg will be consumed from the command line if possible, and
- produced as a single item. If no command-line arg is present, the value from
+* ``'?'``. One argument will be consumed from the command line if possible, and
+ produced as a single item. If no command-line argument is present, the value from
default_ will be produced. Note that for optional arguments, there is an
additional case - the option string is present but not followed by a
- command-line arg. In this case the value from const_ will be produced. Some
+ command-line argument. In this case the value from const_ will be produced. Some
examples to illustrate this::
>>> parser = argparse.ArgumentParser()
@@ -795,7 +799,7 @@
Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
outfile=<open file '<stdout>', mode 'w' at 0x...>)
-* ``'*'``. All command-line args present are gathered into a list. Note that
+* ``'*'``. All command-line arguments present are gathered into a list. Note that
it generally doesn't make much sense to have more than one positional argument
with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
possible. For example::
@@ -809,7 +813,7 @@
* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
list. Additionally, an error message will be generated if there wasn't at
- least one command-line arg present. For example::
+ least one command-line argument present. For example::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
@@ -819,8 +823,8 @@
usage: PROG [-h] foo [foo ...]
PROG: error: too few arguments
-If the ``nargs`` keyword argument is not provided, the number of args consumed
-is determined by the action_. Generally this means a single command-line arg
+If the ``nargs`` keyword argument is not provided, the number of arguments consumed
+is determined by the action_. Generally this means a single command-line argument
will be consumed and a single item (not a list) will be produced.
@@ -837,9 +841,9 @@
* When :meth:`~ArgumentParser.add_argument` is called with option strings
(like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
- argument that can be followed by zero or one command-line args.
+ argument that can be followed by zero or one command-line arguments.
When parsing the command line, if the option string is encountered with no
- command-line arg following it, the value of ``const`` will be assumed instead.
+ command-line argument following it, the value of ``const`` will be assumed instead.
See the nargs_ description for examples.
The ``const`` keyword argument defaults to ``None``.
@@ -851,7 +855,7 @@
All optional arguments and some positional arguments may be omitted at the
command line. The ``default`` keyword argument of
:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
-specifies what value should be used if the command-line arg is not present.
+specifies what value should be used if the command-line argument is not present.
For optional arguments, the ``default`` value is used when the option string
was not present at the command line::
@@ -862,8 +866,8 @@
>>> parser.parse_args(''.split())
Namespace(foo=42)
-For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
-is used when no command-line arg was present::
+For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
+is used when no command-line argument was present::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
@@ -887,12 +891,12 @@
type
^^^^
-By default, ArgumentParser objects read command-line args in as simple strings.
-However, quite often the command-line string should instead be interpreted as
-another type, like a :class:`float`, :class:`int` or :class:`file`. The
+By default, :class:`ArgumentParser` objects read command-line arguments in as simple
+strings. However, quite often the command-line string should instead be
+interpreted as another type, like a :class:`float` or :class:`int`. The
``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
-necessary type-checking and type-conversions to be performed. Many common
-built-in types can be used directly as the value of the ``type`` argument::
+necessary type-checking and type conversions to be performed. Common built-in
+types and functions can be used directly as the value of the ``type`` argument::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
@@ -911,7 +915,7 @@
Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
``type=`` can take any callable that takes a single string argument and returns
-the type-converted value::
+the converted value::
>>> def perfect_square(string):
... value = int(string)
@@ -946,11 +950,11 @@
choices
^^^^^^^
-Some command-line args should be selected from a restricted set of values.
+Some command-line arguments should be selected from a restricted set of values.
These can be handled by passing a container object as the ``choices`` keyword
argument to :meth:`~ArgumentParser.add_argument`. When the command line is
-parsed, arg values will be checked, and an error message will be displayed if
-the arg was not one of the acceptable values::
+parsed, argument values will be checked, and an error message will be displayed if
+the argument was not one of the acceptable values::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', choices='abc')
@@ -1053,7 +1057,7 @@
actions, the dest_ value is used directly, and for optional argument actions,
the dest_ value is uppercased. So, a single positional argument with
``dest='bar'`` will that argument will be referred to as ``bar``. A single
-optional argument ``--foo`` that should be followed by a single command-line arg
+optional argument ``--foo`` that should be followed by a single command-line argument
will be referred to as ``FOO``. An example::
>>> parser = argparse.ArgumentParser()
@@ -1125,10 +1129,10 @@
For optional argument actions, the value of ``dest`` is normally inferred from
the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
-taking the first long option string and stripping away the initial ``'--'``
+taking the first long option string and stripping away the initial ``--``
string. If no long option strings were supplied, ``dest`` will be derived from
-the first short option string by stripping the initial ``'-'`` character. Any
-internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
+the first short option string by stripping the initial ``-`` character. Any
+internal ``-`` characters will be converted to ``_`` characters to make sure
the string is a valid attribute name. The examples below illustrate this
behavior::
@@ -1160,7 +1164,7 @@
created and how they are assigned. See the documentation for
:meth:`add_argument` for details.
- By default, the arg strings are taken from :data:`sys.argv`, and a new empty
+ By default, the argument strings are taken from :data:`sys.argv`, and a new empty
:class:`Namespace` object is created for the attributes.
@@ -1231,15 +1235,15 @@
PROG: error: extra arguments found: badger
-Arguments containing ``"-"``
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Arguments containing ``-``
+^^^^^^^^^^^^^^^^^^^^^^^^^^
The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
the user has clearly made a mistake, but some situations are inherently
-ambiguous. For example, the command-line arg ``'-1'`` could either be an
+ambiguous. For example, the command-line argument ``-1`` could either be an
attempt to specify an option or an attempt to provide a positional argument.
The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
-arguments may only begin with ``'-'`` if they look like negative numbers and
+arguments may only begin with ``-`` if they look like negative numbers and
there are no options in the parser that look like negative numbers::
>>> parser = argparse.ArgumentParser(prog='PROG')
@@ -1272,7 +1276,7 @@
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument
-If you have positional arguments that must begin with ``'-'`` and don't look
+If you have positional arguments that must begin with ``-`` and don't look
like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
:meth:`~ArgumentParser.parse_args` that everything after that is a positional
argument::
@@ -1304,7 +1308,7 @@
Beyond ``sys.argv``
^^^^^^^^^^^^^^^^^^^
-Sometimes it may be useful to have an ArgumentParser parse args other than those
+Sometimes it may be useful to have an ArgumentParser parse arguments other than those
of :data:`sys.argv`. This can be accomplished by passing a list of strings to
:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
interactive prompt::
@@ -1325,11 +1329,14 @@
The Namespace object
^^^^^^^^^^^^^^^^^^^^
-By default, :meth:`~ArgumentParser.parse_args` will return a new object of type
-:class:`Namespace` where the necessary attributes have been set. This class is
-deliberately simple, just an :class:`object` subclass with a readable string
-representation. If you prefer to have dict-like view of the attributes, you
-can use the standard Python idiom via :func:`vars`::
+.. class:: Namespace
+
+ Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
+ an object holding attributes and return it.
+
+This class is deliberately simple, just an :class:`object` subclass with a
+readable string representation. If you prefer to have dict-like view of the
+attributes, you can use the standard Python idiom, :func:`vars`::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
@@ -1387,7 +1394,7 @@
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
- >>> # parse some arg lists
+ >>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
@@ -1396,8 +1403,8 @@
Note that the object returned by :meth:`parse_args` will only contain
attributes for the main parser and the subparser that was selected by the
command line (and not any other subparsers). So in the example above, when
- the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
- present, and when the ``"b"`` command is specified, only the ``foo`` and
+ the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
+ present, and when the ``b`` command is specified, only the ``foo`` and
``baz`` attributes are present.
Similarly, when a help message is requested from a subparser, only the help
@@ -1519,7 +1526,7 @@
The :class:`FileType` factory creates objects that can be passed to the type
argument of :meth:`ArgumentParser.add_argument`. Arguments that have
- :class:`FileType` objects as their type will open command-line args as files
+ :class:`FileType` objects as their type will open command-line arguments as files
with the requested modes and buffer sizes:
>>> parser = argparse.ArgumentParser()
@@ -1633,7 +1640,7 @@
.. method:: ArgumentParser.set_defaults(**kwargs)
Most of the time, the attributes of the object returned by :meth:`parse_args`
- will be fully determined by inspecting the command-line args and the argument
+ will be fully determined by inspecting the command-line arguments and the argument
actions. :meth:`set_defaults` allows some additional
attributes that are determined without any inspection of the command line to
be added::
@@ -1757,7 +1764,7 @@
.. method:: ArgumentParser.error(message)
This method prints a usage message including the *message* to the
- standard output and terminates the program with a status code of 2.
+ standard error and terminates the program with a status code of 2.
.. _argparse-from-optparse:
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index ef36f50..5130d00 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -1,7 +1,5 @@
-.. _ast:
-
-Abstract Syntax Trees
-=====================
+:mod:`ast` --- Abstract Syntax Trees
+====================================
.. module:: ast
:synopsis: Abstract Syntax Tree classes and manipulation.
@@ -15,6 +13,9 @@
.. versionadded:: 2.6
The high-level ``ast`` module containing all helpers.
+**Source code:** :source:`Lib/ast.py`
+
+--------------
The :mod:`ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with each
@@ -28,11 +29,6 @@
compiled into a Python code object using the built-in :func:`compile` function.
-.. seealso::
-
- Latest version of the `ast module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/ast.py?view=markup>`_
-
Node classes
------------
diff --git a/Doc/library/asynchat.rst b/Doc/library/asynchat.rst
index 5096e4c..6f4af41 100644
--- a/Doc/library/asynchat.rst
+++ b/Doc/library/asynchat.rst
@@ -1,4 +1,3 @@
-
:mod:`asynchat` --- Asynchronous socket command/response handler
================================================================
@@ -7,6 +6,9 @@
.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
+**Source code:** :source:`Lib/asynchat.py`
+
+--------------
This module builds on the :mod:`asyncore` infrastructure, simplifying
asynchronous clients and servers and making it easier to handle protocols
diff --git a/Doc/library/asyncore.rst b/Doc/library/asyncore.rst
index 813ac21..33f22d3 100644
--- a/Doc/library/asyncore.rst
+++ b/Doc/library/asyncore.rst
@@ -1,4 +1,3 @@
-
:mod:`asyncore` --- Asynchronous socket handler
===============================================
@@ -10,6 +9,9 @@
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
.. heavily adapted from original documentation by Sam Rushing
+**Source code:** :source:`Lib/asyncore.py`
+
+--------------
This module provides the basic infrastructure for writing asynchronous socket
service clients and servers.
diff --git a/Doc/library/atexit.rst b/Doc/library/atexit.rst
index eab8cd9..c70dcf2 100644
--- a/Doc/library/atexit.rst
+++ b/Doc/library/atexit.rst
@@ -1,4 +1,3 @@
-
:mod:`atexit` --- Exit handlers
===============================
@@ -10,14 +9,15 @@
.. versionadded:: 2.0
+**Source code:** :source:`Lib/atexit.py`
+
+--------------
+
The :mod:`atexit` module defines a single function to register cleanup
functions. Functions thus registered are automatically executed upon normal
-interpreter termination.
-
-.. seealso::
-
- Latest version of the `atexit Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/atexit.py?view=markup>`_
+interpreter termination. The order in which the functions are called is not
+defined; if you have cleanup operations that depend on each other, you should
+wrap them in a function and register that one. This keeps :mod:`atexit` simple.
Note: the functions registered via this module are not called when the program
is killed by a signal not handled by Python, when a Python fatal internal error
diff --git a/Doc/library/basehttpserver.rst b/Doc/library/basehttpserver.rst
index 4662b4f..98b5ce4 100644
--- a/Doc/library/basehttpserver.rst
+++ b/Doc/library/basehttpserver.rst
@@ -18,6 +18,10 @@
module: SimpleHTTPServer
module: CGIHTTPServer
+**Source code:** :source:`Lib/BaseHTTPServer.py`
+
+--------------
+
This module defines two classes for implementing HTTP servers (Web servers).
Usually, this module isn't used directly, but is used as a basis for building
functioning Web servers. See the :mod:`SimpleHTTPServer` and
diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst
index 93304de..bd2b16f 100644
--- a/Doc/library/bdb.rst
+++ b/Doc/library/bdb.rst
@@ -4,6 +4,10 @@
.. module:: bdb
:synopsis: Debugger framework.
+**Source code:** :source:`Lib/bdb.py`
+
+--------------
+
The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.
diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst
index 48cb331..27ab526 100644
--- a/Doc/library/bisect.rst
+++ b/Doc/library/bisect.rst
@@ -7,6 +7,12 @@
.. sectionauthor:: Raymond Hettinger <python at rcn.com>
.. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>
+.. versionadded:: 2.1
+
+**Source code:** :source:`Lib/bisect.py`
+
+--------------
+
This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion. For long lists of items with
expensive comparison operations, this can be an improvement over the more common
@@ -14,13 +20,6 @@
algorithm to do its work. The source code may be most useful as a working
example of the algorithm (the boundary conditions are already right!).
-.. versionadded:: 2.1
-
-.. seealso::
-
- Latest version of the `bisect module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/bisect.py?view=markup>`_
-
The following functions are provided:
diff --git a/Doc/library/calendar.rst b/Doc/library/calendar.rst
index 2245e51..f4f4693 100644
--- a/Doc/library/calendar.rst
+++ b/Doc/library/calendar.rst
@@ -1,4 +1,3 @@
-
:mod:`calendar` --- General calendar-related functions
======================================================
@@ -7,6 +6,9 @@
program.
.. sectionauthor:: Drew Csillag <drew_csillag@geocities.com>
+**Source code:** :source:`Lib/calendar.py`
+
+--------------
This module allows you to output calendars like the Unix :program:`cal` program,
and provides additional useful functions related to the calendar. By default,
@@ -22,10 +24,6 @@
calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
it's the base calendar for all computations.
-.. seealso::
-
- Latest version of the `calendar module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/calendar.py?view=markup>`_
.. class:: Calendar([firstweekday])
diff --git a/Doc/library/cgi.rst b/Doc/library/cgi.rst
index 149cf23..b95f131 100644
--- a/Doc/library/cgi.rst
+++ b/Doc/library/cgi.rst
@@ -13,6 +13,10 @@
single: URL
single: Common Gateway Interface
+**Source code:** :source:`Lib/cgi.py`
+
+--------------
+
Support module for Common Gateway Interface (CGI) scripts.
This module defines a number of utilities for use by CGI scripts written in
diff --git a/Doc/library/cmd.rst b/Doc/library/cmd.rst
index b35373c..ea24122 100644
--- a/Doc/library/cmd.rst
+++ b/Doc/library/cmd.rst
@@ -1,4 +1,3 @@
-
:mod:`cmd` --- Support for line-oriented command interpreters
=============================================================
@@ -6,17 +5,15 @@
:synopsis: Build line-oriented command interpreters.
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
+**Source code:** :source:`Lib/cmd.py`
+
+--------------
The :class:`Cmd` class provides a simple framework for writing line-oriented
command interpreters. These are often useful for test harnesses, administrative
tools, and prototypes that will later be wrapped in a more sophisticated
interface.
-.. seealso::
-
- Latest version of the `cmd module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/cmd.py?view=markup>`_
-
.. class:: Cmd([completekey[, stdin[, stdout]]])
A :class:`Cmd` instance or subclass instance is a line-oriented interpreter
@@ -56,7 +53,7 @@
the line as argument.
The optional argument is a banner or intro string to be issued before the first
- prompt (this overrides the :attr:`intro` class member).
+ prompt (this overrides the :attr:`intro` class attribute).
If the :mod:`readline` module is loaded, input will automatically inherit
:program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back
diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst
index c4152e8..5b29bb1 100644
--- a/Doc/library/codecs.rst
+++ b/Doc/library/codecs.rst
@@ -811,7 +811,7 @@
characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
parts: Marker bits (the most significant bits) and payload bits. The marker bits
-are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are
+are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
encoded like this (with x being payload bits, which when concatenated give the
Unicode character):
@@ -824,12 +824,7 @@
+-----------------------------------+----------------------------------------------+
| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
+-----------------------------------+----------------------------------------------+
-| ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
-+-----------------------------------+----------------------------------------------+
-| ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
-+-----------------------------------+----------------------------------------------+
-| ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
-| | 10xxxxxx |
+| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
+-----------------------------------+----------------------------------------------+
The least significant bit of the Unicode character is the rightmost x bit.
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index 88c4f0f..90f7e3c 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -1,4 +1,3 @@
-
:mod:`collections` --- High-performance container datatypes
===========================================================
@@ -15,6 +14,10 @@
import itertools
__name__ = '<doctest>'
+**Source code:** :source:`Lib/collections.py` and :source:`Lib/_abcoll.py`
+
+--------------
+
This module implements specialized container datatypes providing alternatives to
Python's general purpose built-in containers, :class:`dict`, :class:`list`,
:class:`set`, and :class:`tuple`.
@@ -28,13 +31,10 @@
===================== ==================================================================== ===========================
In addition to the concrete container classes, the collections module provides
-:ref:`abstract-base-classes` that can be used to test whether a class provides a
-particular interface, for example, whether it is hashable or a mapping.
+:ref:`abstract base classes <collections-abstract-base-classes>` that can be
+used to test whether a class provides a particular interface, for example,
+whether it is hashable or a mapping.
-.. seealso::
-
- Latest version of the `collections module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/collections.py?view=markup>`_
:class:`Counter` objects
------------------------
@@ -202,14 +202,14 @@
* `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
in Smalltalk.
- * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_\.
+ * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_.
* `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
tutorial with examples.
* For mathematical operations on multisets and their use cases, see
*Knuth, Donald. The Art of Computer Programming Volume II,
- Section 4.6.3, Exercise 19*\.
+ Section 4.6.3, Exercise 19*.
* To enumerate all distinct multisets of a given size over a given set of
elements, see :func:`itertools.combinations_with_replacement`.
@@ -453,8 +453,7 @@
:class:`defaultdict` objects support the following method in addition to the
standard :class:`dict` operations:
-
- .. method:: defaultdict.__missing__(key)
+ .. method:: __missing__(key)
If the :attr:`default_factory` attribute is ``None``, this raises a
:exc:`KeyError` exception with the *key* as argument.
@@ -474,7 +473,7 @@
:class:`defaultdict` objects support the following instance variable:
- .. attribute:: defaultdict.default_factory
+ .. attribute:: default_factory
This attribute is used by the :meth:`__missing__` method; it is
initialized from the first argument to the constructor, if present, or to
@@ -623,7 +622,9 @@
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
<BLANKLINE>
- def _replace(_self, **kwds):
+ __dict__ = property(_asdict)
+ <BLANKLINE>
+ def _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
@@ -849,23 +850,19 @@
original insertion position is changed and moved to the end::
class LastUpdatedOrderedDict(OrderedDict):
-
'Store items in the order the keys were last added'
+
def __setitem__(self, key, value):
if key in self:
del self[key]
OrderedDict.__setitem__(self, key, value)
-An ordered dictionary can combined with the :class:`Counter` class
+An ordered dictionary can be combined with the :class:`Counter` class
so that the counter remembers the order elements are first encountered::
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
- def __init__(self, iterable=None, **kwds):
- OrderedDict.__init__(self)
- Counter.__init__(self, iterable, **kwds)
-
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
@@ -873,10 +870,10 @@
return self.__class__, (OrderedDict(self),)
-.. _abstract-base-classes:
+.. _collections-abstract-base-classes:
-ABCs - abstract base classes
-----------------------------
+Collections Abstract Base Classes
+---------------------------------
The collections module offers the following :term:`ABCs <abstract base class>`:
@@ -890,7 +887,7 @@
:class:`Sized` ``__len__``
:class:`Callable` ``__call__``
-:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``,
+:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``, ``__iter__``, ``__reversed__``,
:class:`Iterable`, ``index``, and ``count``
:class:`Container`
@@ -1025,9 +1022,6 @@
.. seealso::
- * Latest version of the `Python source code for the collections abstract base classes
- <http://svn.python.org/view/python/branches/release27-maint/Lib/_abcoll.py?view=markup>`_
-
* `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
example built on :class:`MutableSet`.
diff --git a/Doc/library/colorsys.rst b/Doc/library/colorsys.rst
index 2cbc704..dbab706 100644
--- a/Doc/library/colorsys.rst
+++ b/Doc/library/colorsys.rst
@@ -5,6 +5,9 @@
:synopsis: Conversion functions between RGB and other color systems.
.. sectionauthor:: David Ascher <da@python.net>
+**Source code:** :source:`Lib/colorsys.py`
+
+--------------
The :mod:`colorsys` module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in
diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst
index e8eb384..3536f3e 100644
--- a/Doc/library/configparser.rst
+++ b/Doc/library/configparser.rst
@@ -96,6 +96,9 @@
This class does not
support the magical interpolation behavior.
+ All option names are passed through the :meth:`optionxform` method. Its
+ default implementation converts option names to lower case.
+
.. versionadded:: 2.3
.. versionchanged:: 2.6
@@ -116,10 +119,9 @@
*defaults*.
All option names used in interpolation will be passed through the
- :meth:`optionxform` method just like any other option name reference. For
- example, using the default implementation of :meth:`optionxform` (which converts
- option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
- equivalent.
+ :meth:`optionxform` method just like any other option name reference. Using
+ the default implementation of :meth:`optionxform`, the values ``foo %(bar)s``
+ and ``foo %(BAR)s`` are equivalent.
.. versionadded:: 2.3
diff --git a/Doc/library/constants.rst b/Doc/library/constants.rst
index 80e792c..0db8337 100644
--- a/Doc/library/constants.rst
+++ b/Doc/library/constants.rst
@@ -1,3 +1,5 @@
+.. _built-in-consts:
+
Built-in Constants
==================
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst
index c435082..610c0b0 100644
--- a/Doc/library/contextlib.rst
+++ b/Doc/library/contextlib.rst
@@ -7,15 +7,14 @@
.. versionadded:: 2.5
+**Source code:** :source:`Lib/contextlib.py`
+
+--------------
+
This module provides utilities for common tasks involving the :keyword:`with`
statement. For more information see also :ref:`typecontextmanager` and
:ref:`context-managers`.
-.. seealso::
-
- Latest version of the `contextlib Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/contextlib.py?view=markup>`_
-
Functions provided:
diff --git a/Doc/library/cookie.rst b/Doc/library/cookie.rst
index 3bdc61a..480dffa 100644
--- a/Doc/library/cookie.rst
+++ b/Doc/library/cookie.rst
@@ -11,6 +11,9 @@
3.0. The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
+**Source code:** :source:`Lib/Cookie.py`
+
+--------------
The :mod:`Cookie` module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
@@ -191,7 +194,7 @@
.. method:: Morsel.set(key, value, coded_value)
- Set the *key*, *value* and *coded_value* members.
+ Set the *key*, *value* and *coded_value* attributes.
.. method:: Morsel.isReservedKey(K)
diff --git a/Doc/library/cookielib.rst b/Doc/library/cookielib.rst
index 4ca0471..77d6624 100644
--- a/Doc/library/cookielib.rst
+++ b/Doc/library/cookielib.rst
@@ -11,10 +11,11 @@
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
-
.. versionadded:: 2.4
+**Source code:** :source:`Lib/cookielib.py`
+--------------
The :mod:`cookielib` module defines classes for automatic handling of HTTP
cookies. It is useful for accessing web sites that require small pieces of data
diff --git a/Doc/library/crypto.rst b/Doc/library/crypto.rst
index 2cc02c7..21cc251 100644
--- a/Doc/library/crypto.rst
+++ b/Doc/library/crypto.rst
@@ -27,5 +27,5 @@
A.M. Kuchling of further interest; the package contains modules for various
encryption algorithms, most notably AES. These modules are not distributed with
Python but available separately. See the URL
-http://www.amk.ca/python/code/crypto.html for more information.
+http://www.pycrypto.org for more information.
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index f43e166..d94b04e 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -869,10 +869,10 @@
struct cell; /* forward declaration */
- struct {
+ struct cell {
char *name;
struct cell *next;
- } cell;
+ };
The straightforward translation into ctypes code would be this, but it does not
work::
diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst
index 63691db..ecdac9a 100644
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -44,10 +44,6 @@
Module :mod:`curses.textpad`
Editable text widget for curses supporting :program:`Emacs`\ -like bindings.
- Module :mod:`curses.wrapper`
- Convenience function to ensure proper terminal setup and resetting on
- application entry and exit.
-
:ref:`curses-howto`
Tutorial material on using curses with Python, by Andrew Kuchling and Eric
Raymond.
@@ -79,7 +75,7 @@
.. function:: baudrate()
- Returns the output speed of the terminal in bits per second. On software
+ Return the output speed of the terminal in bits per second. On software
terminal emulators it will have a fixed high value. Included for historical
reasons; in former times, it was used to write output loops for time delays and
occasionally to change interfaces depending on the line speed.
@@ -92,7 +88,7 @@
.. function:: can_change_color()
- Returns true or false, depending on whether the programmer can change the colors
+ Return ``True`` or ``False``, depending on whether the programmer can change the colors
displayed by the terminal.
@@ -107,7 +103,7 @@
.. function:: color_content(color_number)
- Returns the intensity of the red, green, and blue (RGB) components in the color
+ Return the intensity of the red, green, and blue (RGB) components in the color
*color_number*, which must be between ``0`` and :const:`COLORS`. A 3-tuple is
returned, containing the R,G,B values for the given color, which will be between
``0`` (no component) and ``1000`` (maximum amount of component).
@@ -115,7 +111,7 @@
.. function:: color_pair(color_number)
- Returns the attribute value for displaying text in the specified color. This
+ Return the attribute value for displaying text in the specified color. This
attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`,
and the other :const:`A_\*` attributes. :func:`pair_number` is the counterpart
to this function.
@@ -123,7 +119,7 @@
.. function:: curs_set(visibility)
- Sets the cursor state. *visibility* can be set to 0, 1, or 2, for invisible,
+ Set the cursor state. *visibility* can be set to 0, 1, or 2, for invisible,
normal, or very visible. If the terminal supports the visibility requested, the
previous cursor state is returned; otherwise, an exception is raised. On many
terminals, the "visible" mode is an underline cursor and the "very visible" mode
@@ -132,7 +128,7 @@
.. function:: def_prog_mode()
- Saves the current terminal mode as the "program" mode, the mode when the running
+ Save the current terminal mode as the "program" mode, the mode when the running
program is using curses. (Its counterpart is the "shell" mode, for when the
program is not in curses.) Subsequent calls to :func:`reset_prog_mode` will
restore this mode.
@@ -140,7 +136,7 @@
.. function:: def_shell_mode()
- Saves the current terminal mode as the "shell" mode, the mode when the running
+ Save the current terminal mode as the "shell" mode, the mode when the running
program is not using curses. (Its counterpart is the "program" mode, when the
program is using curses capabilities.) Subsequent calls to
:func:`reset_shell_mode` will restore this mode.
@@ -148,7 +144,7 @@
.. function:: delay_output(ms)
- Inserts an *ms* millisecond pause in output.
+ Insert an *ms* millisecond pause in output.
.. function:: doupdate()
@@ -179,7 +175,7 @@
.. function:: erasechar()
- Returns the user's current erase character. Under Unix operating systems this
+ Return the user's current erase character. Under Unix operating systems this
is a property of the controlling tty of the curses program, and is not set by
the curses library itself.
@@ -187,7 +183,7 @@
.. function:: filter()
The :func:`.filter` routine, if used, must be called before :func:`initscr` is
- called. The effect is that, during those calls, LINES is set to 1; the
+ called. The effect is that, during those calls, :envvar:`LINES` is set to 1; the
capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home
string is set to the value of cr. The effect is that the cursor is confined to
the current line, and so are screen updates. This may be used for enabling
@@ -213,7 +209,7 @@
method should be call to retrieve the queued mouse event, represented as a
5-tuple ``(id, x, y, z, bstate)``. *id* is an ID value used to distinguish
multiple devices, and *x*, *y*, *z* are the event's coordinates. (*z* is
- currently unused.). *bstate* is an integer value whose bits will be set to
+ currently unused.) *bstate* is an integer value whose bits will be set to
indicate the type of event, and will be the bitwise OR of one or more of the
following constants, where *n* is the button number from 1 to 4:
:const:`BUTTONn_PRESSED`, :const:`BUTTONn_RELEASED`, :const:`BUTTONn_CLICKED`,
@@ -223,32 +219,32 @@
.. function:: getsyx()
- Returns the current coordinates of the virtual screen cursor in y and x. If
+ Return the current coordinates of the virtual screen cursor in y and x. If
leaveok is currently true, then -1,-1 is returned.
.. function:: getwin(file)
- Reads window related data stored in the file by an earlier :func:`putwin` call.
+ Read window related data stored in the file by an earlier :func:`putwin` call.
The routine then creates and initializes a new window using that data, returning
the new window object.
.. function:: has_colors()
- Returns true if the terminal can display colors; otherwise, it returns false.
+ Return ``True`` if the terminal can display colors; otherwise, return ``False``.
.. function:: has_ic()
- Returns true if the terminal has insert- and delete- character capabilities.
+ Return ``True`` if the terminal has insert- and delete-character capabilities.
This function is included for historical reasons only, as all modern software
terminal emulators have such capabilities.
.. function:: has_il()
- Returns true if the terminal has insert- and delete-line capabilities, or can
+ Return ``True`` if the terminal has insert- and delete-line capabilities, or can
simulate them using scrolling regions. This function is included for
historical reasons only, as all modern software terminal emulators have such
capabilities.
@@ -256,7 +252,7 @@
.. function:: has_key(ch)
- Takes a key value *ch*, and returns true if the current terminal type recognizes
+ Take a key value *ch*, and return ``True`` if the current terminal type recognizes
a key with that value.
@@ -265,13 +261,13 @@
Used for half-delay mode, which is similar to cbreak mode in that characters
typed by the user are immediately available to the program. However, after
blocking for *tenths* tenths of seconds, an exception is raised if nothing has
- been typed. The value of *tenths* must be a number between 1 and 255. Use
+ been typed. The value of *tenths* must be a number between ``1`` and ``255``. Use
:func:`nocbreak` to leave half-delay mode.
.. function:: init_color(color_number, r, g, b)
- Changes the definition of a color, taking the number of the color to be changed
+ Change the definition of a color, taking the number of the color to be changed
followed by three RGB values (for the amounts of red, green, and blue
components). The value of *color_number* must be between ``0`` and
:const:`COLORS`. Each of *r*, *g*, *b*, must be a value between ``0`` and
@@ -282,7 +278,7 @@
.. function:: init_pair(pair_number, fg, bg)
- Changes the definition of a color-pair. It takes three arguments: the number of
+ Change the definition of a color-pair. It takes three arguments: the number of
the color-pair to be changed, the foreground color number, and the background
color number. The value of *pair_number* must be between ``1`` and
``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot
@@ -294,7 +290,7 @@
.. function:: initscr()
- Initialize the library. Returns a :class:`WindowObject` which represents the
+ Initialize the library. Return a :class:`WindowObject` which represents the
whole screen.
.. note::
@@ -303,9 +299,15 @@
cause the interpreter to exit.
+.. function:: is_term_resized(nlines, ncols)
+
+ Return ``True`` if :func:`resize_term` would modify the window structure,
+ ``False`` otherwise.
+
+
.. function:: isendwin()
- Returns true if :func:`endwin` has been called (that is, the curses library has
+ Return ``True`` if :func:`endwin` has been called (that is, the curses library has
been deinitialized).
@@ -321,14 +323,14 @@
.. function:: killchar()
- Returns the user's current line kill character. Under Unix operating systems
+ Return the user's current line kill character. Under Unix operating systems
this is a property of the controlling tty of the curses program, and is not set
by the curses library itself.
.. function:: longname()
- Returns a string containing the terminfo long name field describing the current
+ Return a string containing the terminfo long name field describing the current
terminal. The maximum length of a verbose description is 128 characters. It is
defined only after the call to :func:`initscr`.
@@ -341,14 +343,14 @@
.. function:: mouseinterval(interval)
- Sets the maximum time in milliseconds that can elapse between press and release
- events in order for them to be recognized as a click, and returns the previous
+ Set the maximum time in milliseconds that can elapse between press and release
+ events in order for them to be recognized as a click, and return the previous
interval value. The default value is 200 msec, or one fifth of a second.
.. function:: mousemask(mousemask)
- Sets the mouse events to be reported, and returns a tuple ``(availmask,
+ Set the mouse events to be reported, and return a tuple ``(availmask,
oldmask)``. *availmask* indicates which of the specified mouse events can be
reported; on complete failure it returns 0. *oldmask* is the previous value of
the given window's mouse event mask. If this function is never called, no mouse
@@ -362,7 +364,7 @@
.. function:: newpad(nlines, ncols)
- Creates and returns a pointer to a new pad data structure with the given number
+ Create and return a pointer to a new pad data structure with the given number
of lines and columns. A pad is returned as a window object.
A pad is like a window, except that it is not restricted by the screen size, and
@@ -372,9 +374,9 @@
echoing of input) do not occur. The :meth:`refresh` and :meth:`noutrefresh`
methods of a pad require 6 arguments to specify the part of the pad to be
displayed and the location on the screen to be used for the display. The
- arguments are pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol; the p
+ arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p*
arguments refer to the upper left corner of the pad region to be displayed and
- the s arguments define a clipping box on the screen within which the pad region
+ the *s* arguments define a clipping box on the screen within which the pad region
is to be displayed.
@@ -416,7 +418,7 @@
.. function:: noqiflush()
- When the noqiflush routine is used, normal flush of input and output queues
+ When the :func:`noqiflush` routine is used, normal flush of input and output queues
associated with the INTR, QUIT and SUSP characters will not be done. You may
want to call :func:`noqiflush` in a signal handler if you want output to
continue as though the interrupt had not occurred, after the handler exits.
@@ -429,27 +431,27 @@
.. function:: pair_content(pair_number)
- Returns a tuple ``(fg, bg)`` containing the colors for the requested color pair.
+ Return a tuple ``(fg, bg)`` containing the colors for the requested color pair.
The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``.
.. function:: pair_number(attr)
- Returns the number of the color-pair set by the attribute value *attr*.
+ Return the number of the color-pair set by the attribute value *attr*.
:func:`color_pair` is the counterpart to this function.
.. function:: putp(string)
- Equivalent to ``tputs(str, 1, putchar)``; emits the value of a specified
- terminfo capability for the current terminal. Note that the output of putp
+ Equivalent to ``tputs(str, 1, putchar)``; emit the value of a specified
+ terminfo capability for the current terminal. Note that the output of :func:`putp`
always goes to standard output.
.. function:: qiflush( [flag] )
- If *flag* is false, the effect is the same as calling :func:`noqiflush`. If
- *flag* is true, or no argument is provided, the queues will be flushed when
+ If *flag* is ``False``, the effect is the same as calling :func:`noqiflush`. If
+ *flag* is ``True``, or no argument is provided, the queues will be flushed when
these control characters are read.
@@ -462,26 +464,55 @@
.. function:: reset_prog_mode()
- Restores the terminal to "program" mode, as previously saved by
+ Restore the terminal to "program" mode, as previously saved by
:func:`def_prog_mode`.
.. function:: reset_shell_mode()
- Restores the terminal to "shell" mode, as previously saved by
+ Restore the terminal to "shell" mode, as previously saved by
:func:`def_shell_mode`.
+.. function:: resetty()
+
+ Restore the state of the terminal modes to what it was at the last call to
+ :func:`savetty`.
+
+
+.. function:: resize_term(nlines, ncols)
+
+ Backend function used by :func:`resizeterm`, performing most of the work;
+ when resizing the windows, :func:`resize_term` blank-fills the areas that are
+ extended. The calling application should fill in these areas with
+ appropriate data. The :func:`resize_term` function attempts to resize all
+ windows. However, due to the calling convention of pads, it is not possible
+ to resize these without additional interaction with the application.
+
+
+.. function:: resizeterm(nlines, ncols)
+
+ Resize the standard and current windows to the specified dimensions, and
+ adjusts other bookkeeping data used by the curses library that record the
+ window dimensions (in particular the SIGWINCH handler).
+
+
+.. function:: savetty()
+
+ Save the current state of the terminal modes in a buffer, usable by
+ :func:`resetty`.
+
+
.. function:: setsyx(y, x)
- Sets the virtual screen cursor to *y*, *x*. If *y* and *x* are both -1, then
+ Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both -1, then
leaveok is set.
.. function:: setupterm([termstr, fd])
- Initializes the terminal. *termstr* is a string giving the terminal name; if
- omitted, the value of the TERM environment variable will be used. *fd* is the
+ Initialize the terminal. *termstr* is a string giving the terminal name; if
+ omitted, the value of the :envvar:`TERM` environment variable will be used. *fd* is the
file descriptor to which any initialization sequences will be sent; if not
supplied, the file descriptor for ``sys.stdout`` will be used.
@@ -501,19 +532,19 @@
.. function:: termattrs()
- Returns a logical OR of all video attributes supported by the terminal. This
+ Return a logical OR of all video attributes supported by the terminal. This
information is useful when a curses program needs complete control over the
appearance of the screen.
.. function:: termname()
- Returns the value of the environment variable TERM, truncated to 14 characters.
+ Return the value of the environment variable :envvar:`TERM`, truncated to 14 characters.
.. function:: tigetflag(capname)
- Returns the value of the Boolean capability corresponding to the terminfo
+ Return the value of the Boolean capability corresponding to the terminfo
capability name *capname*. The value ``-1`` is returned if *capname* is not a
Boolean capability, or ``0`` if it is canceled or absent from the terminal
description.
@@ -521,7 +552,7 @@
.. function:: tigetnum(capname)
- Returns the value of the numeric capability corresponding to the terminfo
+ Return the value of the numeric capability corresponding to the terminfo
capability name *capname*. The value ``-2`` is returned if *capname* is not a
numeric capability, or ``-1`` if it is canceled or absent from the terminal
description.
@@ -529,22 +560,22 @@
.. function:: tigetstr(capname)
- Returns the value of the string capability corresponding to the terminfo
+ Return the value of the string capability corresponding to the terminfo
capability name *capname*. ``None`` is returned if *capname* is not a string
capability, or is canceled or absent from the terminal description.
.. function:: tparm(str[,...])
- Instantiates the string *str* with the supplied parameters, where *str* should
- be a parameterized string obtained from the terminfo database. E.g.
- ``tparm(tigetstr("cup"), 5, 3)`` could result in ``'\033[6;4H'``, the exact
+ Instantiate the string *str* with the supplied parameters, where *str* should
+ be a parameterized string obtained from the terminfo database. E.g.
+ ``tparm(tigetstr("cup"), 5, 3)`` could result in ``'\033[6;4H'``, the exact
result depending on terminal type.
.. function:: typeahead(fd)
- Specifies that the file descriptor *fd* be used for typeahead checking. If *fd*
+ Specify that the file descriptor *fd* be used for typeahead checking. If *fd*
is ``-1``, then no typeahead checking is done.
The curses library does "line-breakout optimization" by looking for typeahead
@@ -556,7 +587,7 @@
.. function:: unctrl(ch)
- Returns a string which is a printable representation of the character *ch*.
+ Return a string which is a printable representation of the character *ch*.
Control characters are displayed as a caret followed by the character, for
example as ``^C``. Printing characters are left as they are.
@@ -579,7 +610,7 @@
.. function:: use_env(flag)
If used, this function should be called before :func:`initscr` or newterm are
- called. When *flag* is false, the values of lines and columns specified in the
+ called. When *flag* is ``False``, the values of lines and columns specified in the
terminfo database will be used, even if environment variables :envvar:`LINES`
and :envvar:`COLUMNS` (used by default) are set, or if curses is running in a
window (in which case default behavior would be to use the window size if
@@ -595,6 +626,19 @@
foreground color on the default background.
+.. function:: wrapper(func, ...)
+
+ Initialize curses and call another callable object, *func*, which should be the
+ rest of your curses-using application. If the application raises an exception,
+ this function will restore the terminal to a sane state before re-raising the
+ exception and generating a traceback. The callable object *func* is then passed
+ the main window 'stdscr' as its first argument, followed by any other arguments
+ passed to :func:`wrapper`. Before calling *func*, :func:`wrapper` turns on
+ cbreak mode, turns off echo, enables the terminal keypad, and initializes colors
+ if the terminal has color support. On exit (whether normally or by exception)
+ it restores cooked mode, turns on echo, and disables the terminal keypad.
+
+
.. _curses-window-objects:
Window Objects
@@ -608,7 +652,7 @@
.. note::
- A *character* means a C character (an ASCII code), rather then a Python
+ A *character* means a C character (an ASCII code), rather than a Python
character (a string of length 1). (This note is true whenever the
documentation mentions a character.) The built-in :func:`ord` is handy for
conveying strings to codes.
@@ -650,7 +694,7 @@
.. method:: window.bkgd(ch[, attr])
- Sets the background property of the window to the character *ch*, with
+ Set the background property of the window to the character *ch*, with
attributes *attr*. The change is then applied to every character position in
that window:
@@ -663,7 +707,7 @@
.. method:: window.bkgdset(ch[, attr])
- Sets the window's background. A window's background consists of a character and
+ Set the window's background. A window's background consists of a character and
any combination of attributes. The attribute part of the background is combined
(OR'ed) with all non-blank characters that are written into the window. Both
the character and attribute parts of the background are combined with the blank
@@ -708,12 +752,12 @@
.. method:: window.box([vertch, horch])
Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* and
- bs are *horch*. The default corner characters are always used by this function.
+ *bs* are *horch*. The default corner characters are always used by this function.
.. method:: window.chgat([y, x, ] [num,] attr)
- Sets the attributes of *num* characters at the current cursor position, or at
+ Set the attributes of *num* characters at the current cursor position, or at
position ``(y, x)`` if supplied. If no value of *num* is given or *num* = -1,
the attribute will be set on all the characters to the end of the line. This
function does not move the cursor. The changed line will be touched using the
@@ -723,7 +767,7 @@
.. method:: window.clear()
- Like :meth:`erase`, but also causes the whole window to be repainted upon next
+ Like :meth:`erase`, but also cause the whole window to be repainted upon next
call to :meth:`refresh`.
@@ -746,7 +790,7 @@
.. method:: window.cursyncup()
- Updates the current cursor position of all the ancestors of the window to
+ Update the current cursor position of all the ancestors of the window to
reflect the current cursor position of the window.
@@ -757,14 +801,14 @@
.. method:: window.deleteln()
- Delete the line under the cursor. All following lines are moved up by 1 line.
+ Delete the line under the cursor. All following lines are moved up by one line.
.. method:: window.derwin([nlines, ncols,] begin_y, begin_x)
An abbreviation for "derive window", :meth:`derwin` is the same as calling
:meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin
- of the window, rather than relative to the entire screen. Returns a window
+ of the window, rather than relative to the entire screen. Return a window
object for the derived window.
@@ -776,8 +820,8 @@
.. method:: window.enclose(y, x)
- Tests whether the given pair of screen-relative character-cell coordinates are
- enclosed by the given window, returning true or false. It is useful for
+ Test whether the given pair of screen-relative character-cell coordinates are
+ enclosed by the given window, returning ``True`` or ``False``. It is useful for
determining what subset of the screen windows enclose the location of a mouse
event.
@@ -792,6 +836,11 @@
Return a tuple ``(y, x)`` of co-ordinates of upper-left corner.
+.. method:: window.getbkgd()
+
+ Return the given window's current background character/attribute pair.
+
+
.. method:: window.getch([y, x])
Get a character. Note that the integer returned does *not* have to be in ASCII
@@ -814,8 +863,8 @@
.. method:: window.getparyx()
- Returns the beginning coordinates of this window relative to its parent window
- into two integer variables y and x. Returns ``-1,-1`` if this window has no
+ Return the beginning coordinates of this window relative to its parent window
+ into two integer variables y and x. Return ``-1, -1`` if this window has no
parent.
@@ -838,8 +887,8 @@
.. method:: window.idcok(flag)
- If *flag* is false, curses no longer considers using the hardware insert/delete
- character feature of the terminal; if *flag* is true, use of character insertion
+ If *flag* is ``False``, curses no longer considers using the hardware insert/delete
+ character feature of the terminal; if *flag* is ``True``, use of character insertion
and deletion is enabled. When curses is first initialized, use of character
insert/delete is enabled by default.
@@ -852,7 +901,7 @@
.. method:: window.immedok(flag)
- If *flag* is true, any change in the window image automatically causes the
+ If *flag* is ``True``, any change in the window image automatically causes the
window to be refreshed; you no longer have to call :meth:`refresh` yourself.
However, it may degrade performance considerably, due to repeated calls to
wrefresh. This option is disabled by default.
@@ -872,7 +921,7 @@
.. method:: window.insdelln(nlines)
- Inserts *nlines* lines into the specified window above the current line. The
+ Insert *nlines* lines into the specified window above the current line. The
*nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines
starting with the one under the cursor, and move the remaining lines up. The
bottom *nlines* lines are cleared. The current cursor position remains the
@@ -881,7 +930,7 @@
.. method:: window.insertln()
- Insert a blank line under the cursor. All following lines are moved down by 1
+ Insert a blank line under the cursor. All following lines are moved down by one
line.
@@ -904,23 +953,23 @@
.. method:: window.instr([y, x] [, n])
- Returns a string of characters, extracted from the window starting at the
+ Return a string of characters, extracted from the window starting at the
current cursor position, or at *y*, *x* if specified. Attributes are stripped
- from the characters. If *n* is specified, :meth:`instr` returns return a string
+ from the characters. If *n* is specified, :meth:`instr` returns a string
at most *n* characters long (exclusive of the trailing NUL).
.. method:: window.is_linetouched(line)
- Returns true if the specified line was modified since the last call to
- :meth:`refresh`; otherwise returns false. Raises a :exc:`curses.error`
+ Return ``True`` if the specified line was modified since the last call to
+ :meth:`refresh`; otherwise return ``False``. Raise a :exc:`curses.error`
exception if *line* is not valid for the given window.
.. method:: window.is_wintouched()
- Returns true if the specified window was modified since the last call to
- :meth:`refresh`; otherwise returns false.
+ Return ``True`` if the specified window was modified since the last call to
+ :meth:`refresh`; otherwise return ``False``.
.. method:: window.keypad(yes)
@@ -946,7 +995,7 @@
.. method:: window.mvderwin(y, x)
- Moves the window inside its parent window. The screen-relative parameters of
+ Move the window inside its parent window. The screen-relative parameters of
the window are not changed. This routine is used to display different parts of
the parent window at the same physical position on the screen.
@@ -1004,19 +1053,19 @@
.. method:: window.putwin(file)
- Writes all data associated with the window into the provided file object. This
+ Write all data associated with the window into the provided file object. This
information can be later retrieved using the :func:`getwin` function.
.. method:: window.redrawln(beg, num)
- Indicates that the *num* screen lines, starting at line *beg*, are corrupted and
+ Indicate that the *num* screen lines, starting at line *beg*, are corrupted and
should be completely redrawn on the next :meth:`refresh` call.
.. method:: window.redrawwin()
- Touches the entire window, causing it to be completely redrawn on the next
+ Touch the entire window, causing it to be completely redrawn on the next
:meth:`refresh` call.
@@ -1037,6 +1086,14 @@
*sminrow*, or *smincol* are treated as if they were zero.
+.. method:: window.resize(nlines, ncols)
+
+ Reallocate storage for a curses window to adjust its dimensions to the
+ specified values. If either dimension is larger than the current values, the
+ window's data is filled with blanks that have the current background
+ rendition (as set by :meth:`bkgdset`) merged into them.
+
+
.. method:: window.scroll([lines=1])
Scroll the screen or scrolling region upward by *lines* lines.
@@ -1044,7 +1101,7 @@
.. method:: window.scrollok(flag)
- Controls what happens when the cursor of a window is moved off the edge of the
+ Control what happens when the cursor of a window is moved off the edge of the
window or scrolling region, either as a result of a newline action on the bottom
line, or typing the last character of the last line. If *flag* is false, the
cursor is left on the bottom line. If *flag* is true, the window is scrolled up
@@ -1086,26 +1143,26 @@
.. method:: window.syncdown()
- Touches each location in the window that has been touched in any of its ancestor
+ Touch each location in the window that has been touched in any of its ancestor
windows. This routine is called by :meth:`refresh`, so it should almost never
be necessary to call it manually.
.. method:: window.syncok(flag)
- If called with *flag* set to true, then :meth:`syncup` is called automatically
+ If called with *flag* set to ``True``, then :meth:`syncup` is called automatically
whenever there is a change in the window.
.. method:: window.syncup()
- Touches all locations in ancestors of the window that have been changed in the
+ Touch all locations in ancestors of the window that have been changed in the
window.
.. method:: window.timeout(delay)
- Sets blocking or non-blocking read behavior for the window. If *delay* is
+ Set blocking or non-blocking read behavior for the window. If *delay* is
negative, blocking read is used (which will wait indefinitely for input). If
*delay* is zero, then non-blocking read is used, and -1 will be returned by
:meth:`getch` if no input is waiting. If *delay* is positive, then
@@ -1128,7 +1185,7 @@
.. method:: window.untouchwin()
- Marks all lines in the window as unchanged since the last call to
+ Mark all lines in the window as unchanged since the last call to
:meth:`refresh`.
@@ -1587,7 +1644,7 @@
each keystroke entered with the keystroke as a parameter; command dispatch
is done on the result. This method returns the window contents as a
string; whether blanks in the window are included is affected by the
- :attr:`stripspaces` member.
+ :attr:`stripspaces` attribute.
.. method:: do_command(ch)
@@ -1653,45 +1710,15 @@
.. method:: gather()
- This method returns the window contents as a string; whether blanks in the
+ Return the window contents as a string; whether blanks in the
window are included is affected by the :attr:`stripspaces` member.
.. attribute:: stripspaces
- This data member is a flag which controls the interpretation of blanks in
+ This attribute is a flag which controls the interpretation of blanks in
the window. When it is on, trailing blanks on each line are ignored; any
cursor motion that would land the cursor on a trailing blank goes to the
end of that line instead, and trailing blanks are stripped when the window
contents are gathered.
-
-:mod:`curses.wrapper` --- Terminal handler for curses programs
-==============================================================
-
-.. module:: curses.wrapper
- :synopsis: Terminal configuration wrapper for curses programs.
-.. moduleauthor:: Eric Raymond <esr@thyrsus.com>
-.. sectionauthor:: Eric Raymond <esr@thyrsus.com>
-
-
-.. versionadded:: 1.6
-
-This module supplies one function, :func:`wrapper`, which runs another function
-which should be the rest of your curses-using application. If the application
-raises an exception, :func:`wrapper` will restore the terminal to a sane state
-before re-raising the exception and generating a traceback.
-
-
-.. function:: wrapper(func, ...)
-
- Wrapper function that initializes curses and calls another function, *func*,
- restoring normal keyboard/screen behavior on error. The callable object *func*
- is then passed the main window 'stdscr' as its first argument, followed by any
- other arguments passed to :func:`wrapper`.
-
-Before calling the hook function, :func:`wrapper` turns on cbreak mode, turns
-off echo, enables the terminal keypad, and initializes colors if the terminal
-has color support. On exit (whether normally or by exception) it restores
-cooked mode, turns on echo, and disables the terminal keypad.
-
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 24229bb..8a2920d 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -13,7 +13,7 @@
The :mod:`datetime` module supplies classes for manipulating dates and times in
both simple and complex ways. While date and time arithmetic is supported, the
-focus of the implementation is on efficient member extraction for output
+focus of the implementation is on efficient attribute extraction for output
formatting and manipulation. For related
functionality, see also the :mod:`time` and :mod:`calendar` modules.
@@ -27,8 +27,8 @@
work with, at the cost of ignoring some aspects of reality.
For applications requiring more, :class:`datetime` and :class:`time` objects
-have an optional time zone information member, :attr:`tzinfo`, that can contain
-an instance of a subclass of the abstract :class:`tzinfo` class. These
+have an optional time zone information attribute, :attr:`tzinfo`, that can be
+set to an instance of a subclass of the abstract :class:`tzinfo` class. These
:class:`tzinfo` objects capture information about the offset from UTC time, the
time zone name, and whether Daylight Saving Time is in effect. Note that no
concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
@@ -463,9 +463,9 @@
.. method:: date.replace(year, month, day)
- Return a date with the same value, except for those members given new values by
- whichever keyword arguments are specified. For example, if ``d == date(2002,
- 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
+ Return a date with the same value, except for those parameters given new
+ values by whichever keyword arguments are specified. For example, if ``d ==
+ date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.
.. method:: date.timetuple()
@@ -696,11 +696,13 @@
.. classmethod:: datetime.combine(date, time)
- Return a new :class:`datetime` object whose date members are equal to the given
- :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
- the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
- datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
- object, its time and :attr:`tzinfo` members are ignored.
+ Return a new :class:`datetime` object whose date components are equal to the
+ given :class:`date` object's, and whose time components and :attr:`tzinfo`
+ attributes are equal to the given :class:`time` object's. For any
+ :class:`datetime` object *d*,
+ ``d == datetime.combine(d.date(), d.timetz())``. If date is a
+ :class:`datetime` object, its time components and :attr:`tzinfo` attributes
+ are ignored.
.. classmethod:: datetime.strptime(date_string, format)
@@ -795,43 +797,44 @@
(1)
datetime2 is a duration of timedelta removed from datetime1, moving forward in
time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
- result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
- datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
- would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
- that no time zone adjustments are done even if the input is an aware object.
+ result has the same :attr:`tzinfo` attribute as the input datetime, and
+ datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
+ datetime2.year would be smaller than :const:`MINYEAR` or larger than
+ :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
+ input is an aware object.
(2)
Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
- addition, the result has the same :attr:`tzinfo` member as the input datetime,
- and no time zone adjustments are done even if the input is aware. This isn't
- quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
- can overflow in cases where datetime1 - timedelta does not.
+ addition, the result has the same :attr:`tzinfo` attribute as the input
+ datetime, and no time zone adjustments are done even if the input is aware.
+ This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
+ in isolation can overflow in cases where datetime1 - timedelta does not.
(3)
Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
both operands are naive, or if both are aware. If one is aware and the other is
naive, :exc:`TypeError` is raised.
- If both are naive, or both are aware and have the same :attr:`tzinfo` member,
- the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
+ If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
+ the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
are done in this case.
- If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
- *a* and *b* were first converted to naive UTC datetimes first. The result is
- ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
- b.utcoffset())`` except that the implementation never overflows.
+ If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
+ as if *a* and *b* were first converted to naive UTC datetimes first. The
+ result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
+ - b.utcoffset())`` except that the implementation never overflows.
(4)
*datetime1* is considered less than *datetime2* when *datetime1* precedes
*datetime2* in time.
If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
- If both comparands are aware, and have the same :attr:`tzinfo` member, the
- common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
- both comparands are aware and have different :attr:`tzinfo` members, the
- comparands are first adjusted by subtracting their UTC offsets (obtained from
- ``self.utcoffset()``).
+ If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
+ common :attr:`tzinfo` attribute is ignored and the base datetimes are
+ compared. If both comparands are aware and have different :attr:`tzinfo`
+ attributes, the comparands are first adjusted by subtracting their UTC
+ offsets (obtained from ``self.utcoffset()``).
.. note::
@@ -864,22 +867,22 @@
.. method:: datetime.timetz()
Return :class:`time` object with same hour, minute, second, microsecond, and
- tzinfo members. See also method :meth:`time`.
+ tzinfo attributes. See also method :meth:`time`.
.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
- Return a datetime with the same members, except for those members given new
- values by whichever keyword arguments are specified. Note that ``tzinfo=None``
- can be specified to create a naive datetime from an aware datetime with no
- conversion of date and time members.
+ Return a datetime with the same attributes, except for those attributes given
+ new values by whichever keyword arguments are specified. Note that
+ ``tzinfo=None`` can be specified to create a naive datetime from an aware
+ datetime with no conversion of date and time data.
.. method:: datetime.astimezone(tz)
- Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
- the date and time members so the result is the same UTC time as *self*, but in
- *tz*'s local time.
+ Return a :class:`datetime` object with new :attr:`tzinfo` attribute *tz*,
+ adjusting the date and time data so the result is the same UTC time as
+ *self*, but in *tz*'s local time.
*tz* must be an instance of a :class:`tzinfo` subclass, and its
:meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
@@ -887,18 +890,18 @@
not return ``None``).
If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
- adjustment of date or time members is performed. Else the result is local time
- in time zone *tz*, representing the same UTC time as *self*: after ``astz =
- dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
- and time members as ``dt - dt.utcoffset()``. The discussion of class
- :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
- where this cannot be achieved (an issue only if *tz* models both standard and
- daylight time).
+ adjustment of date or time data is performed. Else the result is local
+ time in time zone *tz*, representing the same UTC time as *self*: after
+ ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
+ the same date and time data as ``dt - dt.utcoffset()``. The discussion
+ of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
+ boundaries where this cannot be achieved (an issue only if *tz* models both
+ standard and daylight time).
If you merely want to attach a time zone object *tz* to a datetime *dt* without
- adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
+ adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
merely want to remove the time zone object from an aware datetime *dt* without
- conversion of date and time members, use ``dt.replace(tzinfo=None)``.
+ conversion of date and time data, use ``dt.replace(tzinfo=None)``.
Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
:class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
@@ -1161,19 +1164,19 @@
.. attribute:: time.min
- The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
+ The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
.. attribute:: time.max
- The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
+ The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
.. attribute:: time.resolution
- The smallest possible difference between non-equal :class:`time` objects,
- ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
- objects is not supported.
+ The smallest possible difference between non-equal :class:`.time` objects,
+ ``timedelta(microseconds=1)``, although note that arithmetic on
+ :class:`.time` objects is not supported.
Instance attributes (read-only):
@@ -1200,7 +1203,7 @@
.. attribute:: time.tzinfo
- The object passed as the tzinfo argument to the :class:`time` constructor, or
+ The object passed as the tzinfo argument to the :class:`.time` constructor, or
``None`` if none was passed.
@@ -1209,14 +1212,14 @@
* comparison of :class:`time` to :class:`time`, where *a* is considered less
than *b* when *a* precedes *b* in time. If one comparand is naive and the other
is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
- the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
- the base times are compared. If both comparands are aware and have different
- :attr:`tzinfo` members, the comparands are first adjusted by subtracting their
- UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
- comparisons from falling back to the default comparison by object address, when
- a :class:`time` object is compared to an object of a different type,
- :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
- latter cases return :const:`False` or :const:`True`, respectively.
+ the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
+ ignored and the base times are compared. If both comparands are aware and
+ have different :attr:`tzinfo` attributes, the comparands are first adjusted by
+ subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
+ to stop mixed-type comparisons from falling back to the default comparison by
+ object address, when a :class:`time` object is compared to an object of a
+ different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
+ ``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
* hash, use as dict key
@@ -1231,10 +1234,10 @@
.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
- Return a :class:`time` with the same value, except for those members given new
- values by whichever keyword arguments are specified. Note that ``tzinfo=None``
- can be specified to create a naive :class:`time` from an aware :class:`time`,
- without conversion of the time members.
+ Return a :class:`.time` with the same value, except for those attributes given
+ new values by whichever keyword arguments are specified. Note that
+ ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
+ aware :class:`.time`, without conversion of the time data.
.. method:: time.isoformat()
@@ -1317,7 +1320,7 @@
An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
constructors for :class:`datetime` and :class:`time` objects. The latter objects
-view their members as being in local time, and the :class:`tzinfo` object
+view their attributes as being in local time, and the :class:`tzinfo` object
supports methods revealing offset of local time from UTC, the name of the time
zone, and DST offset, all relative to a date or time object passed to them.
@@ -1362,9 +1365,9 @@
already been added to the UTC offset returned by :meth:`utcoffset`, so there's
no need to consult :meth:`dst` unless you're interested in obtaining DST info
separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
- member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
- set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
- when crossing time zones.
+ attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
+ should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
+ DST changes when crossing time zones.
An instance *tz* of a :class:`tzinfo` subclass that models both standard and
daylight times must be consistent in this sense:
@@ -1439,11 +1442,11 @@
.. method:: tzinfo.fromutc(self, dt)
- This is called from the default :class:`datetime.astimezone()` implementation.
- When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members
- are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to
- adjust the date and time members, returning an equivalent datetime in *self*'s
- local time.
+ This is called from the default :class:`datetime.astimezone()`
+ implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
+ date and time data are to be viewed as expressing a UTC time. The purpose
+ of :meth:`fromutc` is to adjust the date and time data, returning an
+ equivalent datetime in *self*'s local time.
Most :class:`tzinfo` subclasses should be able to inherit the default
:meth:`fromutc` implementation without problems. It's strong enough to handle
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index 357882f..8ac59f4 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -742,7 +742,7 @@
Normalize the number by stripping the rightmost trailing zeros and
converting any result equal to :const:`Decimal('0')` to
- :const:`Decimal('0e0')`. Used for producing canonical values for members
+ :const:`Decimal('0e0')`. Used for producing canonical values for attributes
of an equivalence class. For example, ``Decimal('32.100')`` and
``Decimal('0.321000e+2')`` both normalize to the equivalent value
``Decimal('32.1')``.
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 9addfe7..8dee901 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -1,21 +1,18 @@
-
:mod:`dis` --- Disassembler for Python bytecode
===============================================
.. module:: dis
:synopsis: Disassembler for Python bytecode.
+**Source code:** :source:`Lib/dis.py`
+
+--------------
The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
disassembling it. The CPython bytecode which this module takes as an
input is defined in the file :file:`Include/opcode.h` and used by the compiler
and the interpreter.
-.. seealso::
-
- Latest version of the `dis module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/dis.py?view=markup>`_
-
.. impl-detail::
Bytecode is an implementation detail of the CPython interpreter! No
diff --git a/Doc/library/doctest.rst b/Doc/library/doctest.rst
index 86804ca..b6d1756 100644
--- a/Doc/library/doctest.rst
+++ b/Doc/library/doctest.rst
@@ -1199,12 +1199,11 @@
.. class:: DocTest(examples, globs, name, filename, lineno, docstring)
A collection of doctest examples that should be run in a single namespace. The
- constructor arguments are used to initialize the member variables of the same
- names.
+ constructor arguments are used to initialize the attributes of the same names.
.. versionadded:: 2.4
- :class:`DocTest` defines the following member variables. They are initialized by
+ :class:`DocTest` defines the following attributes. They are initialized by
the constructor, and should not be modified directly.
@@ -1257,12 +1256,12 @@
.. class:: Example(source, want[, exc_msg][, lineno][, indent][, options])
A single interactive example, consisting of a Python statement and its expected
- output. The constructor arguments are used to initialize the member variables
- of the same names.
+ output. The constructor arguments are used to initialize the attributes of the
+ same names.
.. versionadded:: 2.4
- :class:`Example` defines the following member variables. They are initialized by
+ :class:`Example` defines the following attributes. They are initialized by
the constructor, and should not be modified directly.
@@ -1770,9 +1769,9 @@
An exception raised by :class:`DocTestRunner` to signal that a doctest example's
actual output did not match its expected output. The constructor arguments are
- used to initialize the member variables of the same names.
+ used to initialize the attributes of the same names.
-:exc:`DocTestFailure` defines the following member variables:
+:exc:`DocTestFailure` defines the following attributes:
.. attribute:: DocTestFailure.test
@@ -1794,9 +1793,9 @@
An exception raised by :class:`DocTestRunner` to signal that a doctest
example raised an unexpected exception. The constructor arguments are used
- to initialize the member variables of the same names.
+ to initialize the attributes of the same names.
-:exc:`UnexpectedException` defines the following member variables:
+:exc:`UnexpectedException` defines the following attributes:
.. attribute:: UnexpectedException.test
diff --git a/Doc/library/dummy_thread.rst b/Doc/library/dummy_thread.rst
index 5d89760..a4dba86 100644
--- a/Doc/library/dummy_thread.rst
+++ b/Doc/library/dummy_thread.rst
@@ -10,6 +10,9 @@
converting your sources to 3.0; however, you should consider using the
high-lever :mod:`dummy_threading` module instead.
+**Source code:** :source:`Lib/dummy_thread.py`
+
+--------------
This module provides a duplicate interface to the :mod:`thread` module. It is
meant to be imported when the :mod:`thread` module is not provided on a
diff --git a/Doc/library/dummy_threading.rst b/Doc/library/dummy_threading.rst
index 0ffb687..39ca061 100644
--- a/Doc/library/dummy_threading.rst
+++ b/Doc/library/dummy_threading.rst
@@ -1,10 +1,12 @@
-
:mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module
==============================================================================
.. module:: dummy_threading
:synopsis: Drop-in replacement for the threading module.
+**Source code:** :source:`Lib/dummy_threading.py`
+
+--------------
This module provides a duplicate interface to the :mod:`threading` module. It
is meant to be imported when the :mod:`thread` module is not provided on a
diff --git a/Doc/library/filecmp.rst b/Doc/library/filecmp.rst
index 699e510..25d0701 100644
--- a/Doc/library/filecmp.rst
+++ b/Doc/library/filecmp.rst
@@ -1,4 +1,3 @@
-
:mod:`filecmp` --- File and Directory Comparisons
=================================================
@@ -6,16 +5,14 @@
:synopsis: Compare files efficiently.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
+**Source code:** :source:`Lib/filecmp.py`
+
+--------------
The :mod:`filecmp` module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the :mod:`difflib` module.
-.. seealso::
-
- Latest version of the `filecmp Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/filecmp.py?view=markup>`_
-
The :mod:`filecmp` module defines the following functions:
diff --git a/Doc/library/fileinput.rst b/Doc/library/fileinput.rst
index 709237e..172a643 100644
--- a/Doc/library/fileinput.rst
+++ b/Doc/library/fileinput.rst
@@ -6,6 +6,9 @@
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/fileinput.py`
+
+--------------
This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read or
@@ -44,11 +47,6 @@
returns an accordingly opened file-like object. Two useful hooks are already
provided by this module.
-.. seealso::
-
- Latest version of the `fileinput Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/fileinput.py?view=markup>`_
-
The following function is the primary interface of this module:
diff --git a/Doc/library/fnmatch.rst b/Doc/library/fnmatch.rst
index cb1fa10..4911980 100644
--- a/Doc/library/fnmatch.rst
+++ b/Doc/library/fnmatch.rst
@@ -1,4 +1,3 @@
-
:mod:`fnmatch` --- Unix filename pattern matching
=================================================
@@ -10,6 +9,10 @@
.. index:: module: re
+**Source code:** :source:`Lib/fnmatch.py`
+
+--------------
+
This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module). The
special characters used in shell-style wildcards are:
@@ -34,10 +37,6 @@
a period are not special for this module, and are matched by the ``*`` and ``?``
patterns.
-.. seealso::
-
- Latest version of the `fnmatch Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/fnmatch.py?view=markup>`_
.. function:: fnmatch(filename, pattern)
@@ -95,4 +94,3 @@
Module :mod:`glob`
Unix shell-style path expansion.
-
diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst
index 1ca9a9c..4d10cbd 100644
--- a/Doc/library/fractions.rst
+++ b/Doc/library/fractions.rst
@@ -1,4 +1,3 @@
-
:mod:`fractions` --- Rational numbers
=====================================
@@ -8,6 +7,9 @@
.. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
.. versionadded:: 2.6
+**Source code:** :source:`Lib/fractions.py`
+
+--------------
The :mod:`fractions` module provides support for rational number arithmetic.
diff --git a/Doc/library/ftplib.rst b/Doc/library/ftplib.rst
index b6db983..b8f5b4e 100644
--- a/Doc/library/ftplib.rst
+++ b/Doc/library/ftplib.rst
@@ -9,6 +9,10 @@
pair: FTP; protocol
single: FTP; ftplib (standard module)
+**Source code:** :source:`Lib/ftplib.py`
+
+--------------
+
This module defines the class :class:`FTP` and a few related items. The
:class:`FTP` class implements the client side of the FTP protocol. You can use
this to write Python programs that perform a variety of automated FTP jobs, such
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index 4b63c9f..a5dacc6 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -298,19 +298,18 @@
The resulting list is sorted alphabetically. For example:
>>> import struct
- >>> dir() # doctest: +SKIP
+ >>> dir() # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
- >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE
+ >>> dir(struct) # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
'unpack', 'unpack_from']
- >>> class Foo(object):
- ... def __dir__(self):
- ... return ["kan", "ga", "roo"]
- ...
- >>> f = Foo()
- >>> dir(f)
- ['ga', 'kan', 'roo']
+ >>> class Shape(object):
+ def __dir__(self):
+ return ['area', 'perimeter', 'location']
+ >>> s = Shape()
+ >>> dir(s)
+ ['area', 'perimeter', 'location']
.. note::
@@ -342,20 +341,25 @@
:term:`iterator`, or some other object which supports iteration. The
:meth:`!next` method of the iterator returned by :func:`enumerate` returns a
tuple containing a count (from *start* which defaults to 0) and the
- corresponding value obtained from iterating over *iterable*.
- :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``,
- ``(1, seq[1])``, ``(2, seq[2])``, .... For example:
+ values obtained from iterating over *sequence*::
- >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
- ... print i, season
- 0 Spring
- 1 Summer
- 2 Fall
- 3 Winter
+ >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
+ >>> list(enumerate(seasons))
+ [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
+ >>> list(enumerate(seasons, start=1))
+ [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
+
+ Equivalent to::
+
+ def enumerate(sequence, start=0):
+ n = start
+ for elem in sequence:
+ yield n, elem
+ n += 1
.. versionadded:: 2.3
- .. versionadded:: 2.6
- The *start* parameter.
+ .. versionchanged:: 2.6
+ The *start* parameter was added.
.. function:: eval(expression[, globals[, locals]])
@@ -579,20 +583,19 @@
Two objects with non-overlapping lifetimes may have the same :func:`id`
value.
- .. impl-detail:: This is the address of the object.
+ .. impl-detail:: This is the address of the object in memory.
.. function:: input([prompt])
Equivalent to ``eval(raw_input(prompt))``.
- .. warning::
+ .. note::
- This function is not safe from user errors! It expects a valid Python
- expression as input; if the input is not syntactically valid, a
- :exc:`SyntaxError` will be raised. Other exceptions may be raised if there is an
- error during evaluation. (On the other hand, sometimes this is exactly what you
- need when writing a quick script for expert use.)
+ This function does not catch user errors. It expects a valid Python
+ expression as input. If the input is not syntactically valid, a
+ :exc:`SyntaxError` will be raised. Other exceptions may be raised if there
+ is an error during evaluation.
If the :mod:`readline` module was loaded, then :func:`input` will use it to
provide elaborate line editing and history features.
@@ -621,9 +624,11 @@
.. function:: isinstance(object, classinfo)
Return true if the *object* argument is an instance of the *classinfo* argument,
- or of a (direct or indirect) subclass thereof. Also return true if *classinfo*
+ or of a (direct, indirect or :term:`virtual <abstract base class>`) subclass
+ thereof. Also return true if *classinfo*
is a type object (new-style class) and *object* is an object of that type or of
- a (direct or indirect) subclass thereof. If *object* is not a class instance or
+ a (direct, indirect or :term:`virtual <abstract base class>`) subclass
+ thereof. If *object* is not a class instance or
an object of the given type, the function always returns false. If *classinfo*
is neither a class object nor a type object, it may be a tuple of class or type
objects, or may recursively contain other such tuples (other sequence types are
@@ -636,7 +641,8 @@
.. function:: issubclass(class, classinfo)
- Return true if *class* is a subclass (direct or indirect) of *classinfo*. A
+ Return true if *class* is a subclass (direct, indirect or :term:`virtual
+ <abstract base class>`) of *classinfo*. A
class is considered a subclass of itself. *classinfo* may be a tuple of class
objects, in which case every entry in *classinfo* will be checked. In any other
case, a :exc:`TypeError` exception is raised.
@@ -660,10 +666,10 @@
One useful application of the second form of :func:`iter` is to read lines of
a file until a certain line is reached. The following example reads a file
- until ``"STOP"`` is reached: ::
+ until the :meth:`readline` method returns an empty string::
- with open("mydata.txt") as fp:
- for line in iter(fp.readline, "STOP"):
+ with open('mydata.txt') as fp:
+ for line in iter(fp.readline, ''):
process_line(line)
.. versionadded:: 2.2
@@ -793,7 +799,7 @@
Formerly only returned an unsigned literal.
-.. function:: open(filename[, mode[, bufsize]])
+.. function:: open(name[, mode[, buffering]])
Open a file, returning an object of the :class:`file` type described in
section :ref:`bltin-file-objects`. If the file cannot be opened,
@@ -801,7 +807,7 @@
:func:`open` instead of invoking the :class:`file` constructor directly.
The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`:
- *filename* is the file name to be opened, and *mode* is a string indicating how
+ *name* is the file name to be opened, and *mode* is a string indicating how
the file is to be opened.
The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for
@@ -822,9 +828,9 @@
single: buffer size, I/O
single: I/O control; buffering
- The optional *bufsize* argument specifies the file's desired buffer size: 0
+ The optional *buffering* argument specifies the file's desired buffer size: 0
means unbuffered, 1 means line buffered, any other positive value means use a
- buffer of (approximately) that size. A negative *bufsize* means to use the
+ buffer of (approximately) that size. A negative *buffering* means to use the
system default, which is usually line buffered for tty devices and fully
buffered for other files. If omitted, the system default is used. [#]_
@@ -1241,8 +1247,9 @@
It can be called either on the class (such as ``C.f()``) or on an instance (such
as ``C().f()``). The instance is ignored except for its class.
- Static methods in Python are similar to those found in Java or C++. For a more
- advanced concept, see :func:`classmethod` in this section.
+ Static methods in Python are similar to those found in Java or C++. Also see
+ :func:`classmethod` for a variant that is useful for creating alternate
+ class constructors.
For more information on static methods, consult the documentation on the
standard type hierarchy in :ref:`types`.
@@ -1335,6 +1342,10 @@
argument form specifies the arguments exactly and makes the appropriate
references.
+ For practical suggestions on how to design cooperative classes using
+ :func:`super`, see `guide to using super()
+ <http://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.
+
.. versionadded:: 2.2
@@ -1464,7 +1475,7 @@
also requires that the number of elements fit in a native C long. If a
larger range is needed, an alternate version can be crafted using the
:mod:`itertools` module: ``islice(count(start, step),
- (stop-start+step-1)//step)``.
+ (stop-start+step-1+2*(step<0))//step)``.
.. function:: zip([iterable, ...])
diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst
index 787c000..10c984f 100644
--- a/Doc/library/functools.rst
+++ b/Doc/library/functools.rst
@@ -8,18 +8,16 @@
.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
-
.. versionadded:: 2.5
+**Source code:** :source:`Lib/functools.py`
+
+--------------
+
The :mod:`functools` module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.
-.. seealso::
-
- Latest version of the `functools Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/functools.py?view=markup>`_
-
The :mod:`functools` module defines the following functions:
.. function:: cmp_to_key(func)
diff --git a/Doc/library/getopt.rst b/Doc/library/getopt.rst
index 4d65c79..11385ff 100644
--- a/Doc/library/getopt.rst
+++ b/Doc/library/getopt.rst
@@ -1,4 +1,3 @@
-
:mod:`getopt` --- C-style parser for command line options
=========================================================
@@ -6,6 +5,10 @@
:synopsis: Portable parser for command line options; support both short and long option
names.
+**Source code:** :source:`Lib/getopt.py`
+
+--------------
+
.. note::
The :mod:`getopt` module is a parser for command line options whose API is
designed to be familiar to users of the C :cfunc:`getopt` function. Users who
@@ -19,9 +22,6 @@
options similar to those supported by GNU software may be used as well via an
optional third argument.
-A more convenient, flexible, and powerful alternative is the
-:mod:`optparse` module.
-
This module provides two functions and an
exception:
diff --git a/Doc/library/gettext.rst b/Doc/library/gettext.rst
index f64631f..9b4eb0c 100644
--- a/Doc/library/gettext.rst
+++ b/Doc/library/gettext.rst
@@ -1,4 +1,3 @@
-
:mod:`gettext` --- Multilingual internationalization services
=============================================================
@@ -7,6 +6,9 @@
.. moduleauthor:: Barry A. Warsaw <barry@zope.com>
.. sectionauthor:: Barry A. Warsaw <barry@zope.com>
+**Source code:** :source:`Lib/gettext.py`
+
+--------------
The :mod:`gettext` module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
@@ -298,7 +300,7 @@
.. method:: lngettext(singular, plural, n)
- If a fallback has been set, forward :meth:`ngettext` to the
+ If a fallback has been set, forward :meth:`lngettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
@@ -754,8 +756,8 @@
.. [#] See the footnote for :func:`bindtextdomain` above.
.. [#] François Pinard has written a program called :program:`xpot` which does a
- similar job. It is available as part of his :program:`po-utils` package at http
- ://po-utils.progiciels-bpi.ca/.
+ similar job. It is available as part of his `po-utils package
+ <http://po-utils.progiciels-bpi.ca/>`_.
.. [#] :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt` except that
it provides a simpler, all-Python implementation. With this and
diff --git a/Doc/library/glob.rst b/Doc/library/glob.rst
index 1ef9a31..68cc9f0 100644
--- a/Doc/library/glob.rst
+++ b/Doc/library/glob.rst
@@ -1,4 +1,3 @@
-
:mod:`glob` --- Unix style pathname pattern expansion
=====================================================
@@ -8,6 +7,10 @@
.. index:: single: filenames; pathname expansion
+**Source code:** :source:`Lib/glob.py`
+
+--------------
+
The :mod:`glob` module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell. No tilde expansion is done, but
``*``, ``?``, and character ranges expressed with ``[]`` will be correctly
@@ -16,10 +19,6 @@
subshell. (For tilde and shell variable expansion, use
:func:`os.path.expanduser` and :func:`os.path.expandvars`.)
-.. seealso::
-
- Latest version of the `glob module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/glob.py?view=markup>`_
.. function:: glob(pathname)
diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst
index 17896c3..e074bfc 100644
--- a/Doc/library/gzip.rst
+++ b/Doc/library/gzip.rst
@@ -4,6 +4,10 @@
.. module:: gzip
:synopsis: Interfaces for gzip compression and decompression using file objects.
+**Source code:** :source:`Lib/gzip.py`
+
+--------------
+
This module provides a simple interface to compress and decompress files just
like the GNU programs :program:`gzip` and :program:`gunzip` would.
@@ -58,7 +62,7 @@
time is used. This module ignores the timestamp when decompressing;
however, some programs, such as :program:`gunzip`\ , make use of it.
The format of the timestamp is the same as that of the return value of
- ``time.time()`` and of the ``st_mtime`` member of the object returned
+ ``time.time()`` and of the ``st_mtime`` attribute of the object returned
by ``os.stat()``.
Calling a :class:`GzipFile` object's :meth:`close` method does not close
diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst
index 51ac93b..063ad59 100644
--- a/Doc/library/hashlib.rst
+++ b/Doc/library/hashlib.rst
@@ -1,4 +1,3 @@
-
:mod:`hashlib` --- Secure hashes and message digests
====================================================
@@ -14,6 +13,10 @@
single: message digest, MD5
single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512
+**Source code:** :source:`Lib/hashlib.py`
+
+--------------
+
This module implements a common interface to many different secure hash and
message digest algorithms. Included are the FIPS secure hash algorithms SHA1,
SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5
diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst
index a6b9ba2..f0723b7 100644
--- a/Doc/library/heapq.rst
+++ b/Doc/library/heapq.rst
@@ -10,14 +10,13 @@
.. versionadded:: 2.3
+**Source code:** :source:`Lib/heapq.py`
+
+--------------
+
This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.
-.. seealso::
-
- Latest version of the `heapq Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/heapq.py?view=markup>`_
-
Heaps are binary trees for which every parent node has a value less than or
equal to any of its children. This implementation uses arrays for which
``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
@@ -188,36 +187,36 @@
with a dictionary pointing to an entry in the queue.
Removing the entry or changing its priority is more difficult because it would
-break the heap structure invariants. So, a possible solution is to mark an
-entry as invalid and optionally add a new entry with the revised priority::
+break the heap structure invariants. So, a possible solution is to mark the
+existing entry as removed and add a new entry with the revised priority::
- pq = [] # the priority queue list
- counter = itertools.count(1) # unique sequence count
- task_finder = {} # mapping of tasks to entries
- INVALID = 0 # mark an entry as deleted
+ pq = [] # list of entries arranged in a heap
+ entry_finder = {} # mapping of tasks to entries
+ REMOVED = '<removed-task>' # placeholder for a removed task
+ counter = itertools.count() # unique sequence count
- def add_task(priority, task, count=None):
- if count is None:
- count = next(counter)
+ def add_task(task, priority=0):
+ 'Add a new task or update the priority of an existing task'
+ if task in entry_finder:
+ remove_task(task)
+ count = next(counter)
entry = [priority, count, task]
- task_finder[task] = entry
+ entry_finder[task] = entry
heappush(pq, entry)
- def get_top_priority():
- while True:
+ def remove_task(task):
+ 'Mark an existing task as REMOVED. Raise KeyError if not found.'
+ entry = entry_finder.pop(task)
+ entry[-1] = REMOVED
+
+ def pop_task():
+ 'Remove and return the lowest priority task. Raise KeyError if empty.'
+ while pq:
priority, count, task = heappop(pq)
- del task_finder[task]
- if count is not INVALID:
+ if task is not REMOVED:
+ del entry_finder[task]
return task
-
- def delete_task(task):
- entry = task_finder[task]
- entry[1] = INVALID
-
- def reprioritize(priority, task):
- entry = task_finder[task]
- add_task(priority, task, entry[1])
- entry[1] = INVALID
+ raise KeyError('pop from an empty priority queue')
Theory
diff --git a/Doc/library/hmac.rst b/Doc/library/hmac.rst
index 480d0a7..968b7a4 100644
--- a/Doc/library/hmac.rst
+++ b/Doc/library/hmac.rst
@@ -1,4 +1,3 @@
-
:mod:`hmac` --- Keyed-Hashing for Message Authentication
========================================================
@@ -10,6 +9,10 @@
.. versionadded:: 2.2
+**Source code:** :source:`Lib/hmac.py`
+
+--------------
+
This module implements the HMAC algorithm as described by :rfc:`2104`.
diff --git a/Doc/library/htmllib.rst b/Doc/library/htmllib.rst
index f6ed564..f253d12 100644
--- a/Doc/library/htmllib.rst
+++ b/Doc/library/htmllib.rst
@@ -165,10 +165,13 @@
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
+**Source code:** :source:`Lib/htmlentitydefs.py`
+
+--------------
This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to
-provide the :attr:`entitydefs` member of the :class:`HTMLParser` class. The
+provide the :attr:`entitydefs` attribute of the :class:`HTMLParser` class. The
definition provided here contains all the entities defined by XHTML 1.0 that
can be handled using simple textual substitution in the Latin-1 character set
(ISO-8859-1).
diff --git a/Doc/library/htmlparser.rst b/Doc/library/htmlparser.rst
index c114bf8..0cdc7ca 100644
--- a/Doc/library/htmlparser.rst
+++ b/Doc/library/htmlparser.rst
@@ -18,6 +18,10 @@
single: HTML
single: XHTML
+**Source code:** :source:`Lib/HTMLParser.py`
+
+--------------
+
This module defines a class :class:`HTMLParser` which serves as the basis for
parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser
diff --git a/Doc/library/httplib.rst b/Doc/library/httplib.rst
index 436857c..fc26f24 100644
--- a/Doc/library/httplib.rst
+++ b/Doc/library/httplib.rst
@@ -16,6 +16,10 @@
.. index:: module: urllib
+**Source code:** :source:`Lib/httplib.py`
+
+--------------
+
This module defines classes which implement the client side of the HTTP and
HTTPS protocols. It is normally not used directly --- the module :mod:`urllib`
uses it to handle URLs that use HTTP and HTTPS.
@@ -488,9 +492,16 @@
an argument.
-.. method:: HTTPConnection.endheaders()
+.. method:: HTTPConnection.endheaders(message_body=None)
- Send a blank line to the server, signalling the end of the headers.
+ Send a blank line to the server, signalling the end of the headers. The
+ optional *message_body* argument can be used to pass a message body
+ associated with the request. The message body will be sent in the same
+ packet as the message headers if it is string, otherwise it is sent in a
+ separate packet.
+
+ .. versionchanged:: 2.7
+ *message_body* was added.
.. method:: HTTPConnection.send(data)
@@ -588,14 +599,16 @@
Here is an example session that shows how to ``POST`` requests::
>>> import httplib, urllib
- >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
+ >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
- >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
- >>> conn.request("POST", "/cgi-bin/query", params, headers)
+ >>> conn = httplib.HTTPConnection("bugs.python.org")
+ >>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
- 200 OK
+ 302 Found
>>> data = response.read()
+ >>> data
+ 'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()
diff --git a/Doc/library/imaplib.rst b/Doc/library/imaplib.rst
index 95bdc70..9fcbaaa 100644
--- a/Doc/library/imaplib.rst
+++ b/Doc/library/imaplib.rst
@@ -16,6 +16,10 @@
pair: IMAP4_SSL; protocol
pair: IMAP4_stream; protocol
+**Source code:** :source:`Lib/imaplib.py`
+
+--------------
+
This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
implement a large subset of the IMAP4rev1 client protocol as defined in
diff --git a/Doc/library/imghdr.rst b/Doc/library/imghdr.rst
index 90a8304..20f789f 100644
--- a/Doc/library/imghdr.rst
+++ b/Doc/library/imghdr.rst
@@ -1,10 +1,12 @@
-
:mod:`imghdr` --- Determine the type of an image
================================================
.. module:: imghdr
:synopsis: Determine the type of image contained in a file or byte stream.
+**Source code:** :source:`Lib/imghdr.py`
+
+--------------
The :mod:`imghdr` module determines the type of image contained in a file or
byte stream.
diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst
index 850ff08..e05618e 100644
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -1,4 +1,3 @@
-
:mod:`inspect` --- Inspect live objects
=======================================
@@ -10,6 +9,10 @@
.. versionadded:: 2.1
+**Source code:** :source:`Lib/inspect.py`
+
+--------------
+
The :mod:`inspect` module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects. For example, it can help you
diff --git a/Doc/library/io.rst b/Doc/library/io.rst
index 3cfaaed..969b408 100644
--- a/Doc/library/io.rst
+++ b/Doc/library/io.rst
@@ -407,8 +407,8 @@
:class:`RawIOBase` implementation, but wrap one, like
:class:`BufferedWriter` and :class:`BufferedReader` do.
- :class:`BufferedIOBase` provides or overrides these members in addition to
- those from :class:`IOBase`:
+ :class:`BufferedIOBase` provides or overrides these methods and attribute in
+ addition to those from :class:`IOBase`:
.. attribute:: raw
@@ -604,25 +604,6 @@
if the buffer needs to be written out but the raw stream blocks.
-.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
-
- A buffered I/O object giving a combined, higher-level access to two
- sequential :class:`RawIOBase` objects: one readable, the other writeable.
- It is useful for pairs of unidirectional communication channels
- (pipes, for instance). It inherits :class:`BufferedIOBase`.
-
- *reader* and *writer* are :class:`RawIOBase` objects that are readable and
- writeable respectively. If the *buffer_size* is omitted it defaults to
- :data:`DEFAULT_BUFFER_SIZE`.
-
- A fourth argument, *max_buffer_size*, is supported, but unused and
- deprecated.
-
- :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
- except for :meth:`~BufferedIOBase.detach`, which raises
- :exc:`UnsupportedOperation`.
-
-
.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
A buffered interface to random access streams. It inherits
@@ -639,6 +620,29 @@
:class:`BufferedWriter` can do.
+.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
+
+ A buffered I/O object combining two unidirectional :class:`RawIOBase`
+ objects -- one readable, the other writeable -- into a single bidirectional
+ endpoint. It inherits :class:`BufferedIOBase`.
+
+ *reader* and *writer* are :class:`RawIOBase` objects that are readable and
+ writeable respectively. If the *buffer_size* is omitted it defaults to
+ :data:`DEFAULT_BUFFER_SIZE`.
+
+ A fourth argument, *max_buffer_size*, is supported, but unused and
+ deprecated.
+
+ :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
+ except for :meth:`~BufferedIOBase.detach`, which raises
+ :exc:`UnsupportedOperation`.
+
+ .. warning::
+ :class:`BufferedRWPair` does not attempt to synchronize accesses to
+ its underlying raw streams. You should not pass it the same object
+ as reader and writer; use :class:`BufferedRandom` instead.
+
+
Text I/O
--------
diff --git a/Doc/library/keyword.rst b/Doc/library/keyword.rst
index 3b69d0b..173db23 100644
--- a/Doc/library/keyword.rst
+++ b/Doc/library/keyword.rst
@@ -1,10 +1,12 @@
-
:mod:`keyword` --- Testing for Python keywords
==============================================
.. module:: keyword
:synopsis: Test whether a string is a keyword in Python.
+**Source code:** :source:`Lib/keyword.py`
+
+--------------
This module allows a Python program to determine if a string is a keyword.
@@ -19,9 +21,3 @@
Sequence containing all the keywords defined for the interpreter. If any
keywords are defined to only be active when particular :mod:`__future__`
statements are in effect, these will be included as well.
-
-
-.. seealso::
-
- Latest version of the `keyword module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/keyword.py?view=markup>`_
diff --git a/Doc/library/linecache.rst b/Doc/library/linecache.rst
index 8ebee05..39385f9 100644
--- a/Doc/library/linecache.rst
+++ b/Doc/library/linecache.rst
@@ -6,17 +6,15 @@
:synopsis: This module provides random access to individual lines from text files.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
+**Source code:** :source:`Lib/linecache.py`
+
+--------------
The :mod:`linecache` module allows one to get any line from any file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file. This is used by the :mod:`traceback` module
to retrieve source lines for inclusion in the formatted traceback.
-.. seealso::
-
- Latest version of the `linecache module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/linecache.py?view=markup>`_
-
The :mod:`linecache` module defines the following functions:
diff --git a/Doc/library/logging.config.rst b/Doc/library/logging.config.rst
index 500c736..8b39be4 100644
--- a/Doc/library/logging.config.rst
+++ b/Doc/library/logging.config.rst
@@ -516,6 +516,31 @@
to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
fails.
+
+.. _logging-import-resolution:
+
+Import resolution and custom importers
+""""""""""""""""""""""""""""""""""""""
+
+Import resolution, by default, uses the builtin :func:`__import__` function
+to do its importing. You may want to replace this with your own importing
+mechanism: if so, you can replace the :attr:`importer` attribute of the
+:class:`DictConfigurator` or its superclass, the
+:class:`BaseConfigurator` class. However, you need to be
+careful because of the way functions are accessed from classes via
+descriptors. If you are using a Python callable to do your imports, and you
+want to define it at class level rather than instance level, you need to wrap
+it with :func:`staticmethod`. For example::
+
+ from importlib import import_module
+ from logging.config import BaseConfigurator
+
+ BaseConfigurator.importer = staticmethod(import_module)
+
+You don't need to wrap with :func:`staticmethod` if you're setting the import
+callable on a configurator *instance*.
+
+
.. _logging-config-fileformat:
Configuration file format
diff --git a/Doc/library/logging.handlers.rst b/Doc/library/logging.handlers.rst
index 9db262a..1a14499 100644
--- a/Doc/library/logging.handlers.rst
+++ b/Doc/library/logging.handlers.rst
@@ -613,8 +613,14 @@
port, use the (host, port) tuple format for the *mailhost* argument. If you
use a string, the standard SMTP port is used. If your SMTP server requires
authentication, you can specify a (username, password) tuple for the
- *credentials* argument. If *secure* is True, then the handler will attempt
- to use TLS for the email transmission.
+ *credentials* argument.
+
+ To specify the use of a secure protocol (TLS), pass in a tuple to the
+ *secure* argument. This will only be used when authentication credentials are
+ supplied. The tuple should be either an empty tuple, or a single-value tuple
+ with the name of a keyfile, or a 2-value tuple with the names of the keyfile
+ and certificate file. (This tuple is passed to the
+ :meth:`smtplib.SMTP.starttls` method.)
.. versionchanged:: 2.6
*credentials* was added.
diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst
index 7578d6a..b666573 100644
--- a/Doc/library/logging.rst
+++ b/Doc/library/logging.rst
@@ -416,6 +416,13 @@
record. Otherwise, the ISO8601 format is used. The resulting string is
returned.
+ This function uses a user-configurable function to convert the creation
+ time to a tuple. By default, :func:`time.localtime` is used; to change
+ this for a particular formatter instance, set the ``converter`` attribute
+ to a function with the same signature as :func:`time.localtime` or
+ :func:`time.gmtime`. To change it for all formatters, for example if you
+ want all logging times to be shown in GMT, set the ``converter``
+ attribute in the ``Formatter`` class.
.. method:: formatException(exc_info)
@@ -491,6 +498,9 @@
:param name: The name of the logger used to log the event represented by
this LogRecord.
:param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
+ Note that this is converted to *two* attributes of the LogRecord:
+ ``levelno`` for the numeric value and ``levelname`` for the
+ corresponding level name.
:param pathname: The full pathname of the source file where the logging call
was made.
:param lineno: The line number in the source file where the logging call was
diff --git a/Doc/library/mailcap.rst b/Doc/library/mailcap.rst
index 8dcb1ec..5507211 100644
--- a/Doc/library/mailcap.rst
+++ b/Doc/library/mailcap.rst
@@ -4,7 +4,9 @@
.. module:: mailcap
:synopsis: Mailcap file handling.
+**Source code:** :source:`Lib/mailcap.py`
+--------------
Mailcap files are used to configure how MIME-aware applications such as mail
readers and Web browsers react to files with different MIME types. (The name
diff --git a/Doc/library/mimetypes.rst b/Doc/library/mimetypes.rst
index 956a1f1..69f8434 100644
--- a/Doc/library/mimetypes.rst
+++ b/Doc/library/mimetypes.rst
@@ -9,6 +9,10 @@
.. index:: pair: MIME; content type
+**Source code:** :source:`Lib/mimetypes.py`
+
+--------------
+
The :mod:`mimetypes` module converts between a filename or URL and the MIME type
associated with the filename extension. Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index 125b34f..55861f9 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -23,6 +23,12 @@
:func:`os.open` function, which returns a file descriptor directly (the file
still needs to be closed when done).
+.. note::
+ If you want to create a memory-mapping for a writable, buffered file, you
+ should :func:`~io.IOBase.flush` the file first. This is necessary to ensure
+ that local modifications to the buffers are actually available to the
+ mapping.
+
For both the Unix and Windows versions of the constructor, *access* may be
specified as an optional keyword parameter. *access* accepts one of three
values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
@@ -94,6 +100,10 @@
defaults to 0. *offset* must be a multiple of the PAGESIZE or
ALLOCATIONGRANULARITY.
+ To ensure validity of the created memory mapping the file specified
+ by the descriptor *fileno* is internally automatically synchronized
+ with physical backing store on Mac OS X and OpenVMS.
+
This example shows a simple way of using :class:`mmap`::
import mmap
diff --git a/Doc/library/modulefinder.rst b/Doc/library/modulefinder.rst
index a086206..40bf60f 100644
--- a/Doc/library/modulefinder.rst
+++ b/Doc/library/modulefinder.rst
@@ -1,16 +1,17 @@
-
:mod:`modulefinder` --- Find modules used by a script
=====================================================
+.. module:: modulefinder
+ :synopsis: Find modules used by a script.
.. sectionauthor:: A.M. Kuchling <amk@amk.ca>
-.. module:: modulefinder
- :synopsis: Find modules used by a script.
-
-
.. versionadded:: 2.3
+**Source code:** :source:`Lib/modulefinder.py`
+
+--------------
+
This module provides a :class:`ModuleFinder` class that can be used to determine
the set of modules imported by a script. ``modulefinder.py`` can also be run as
a script, giving the filename of a Python script as its argument, after which a
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index 26d0b3d..30c4b10 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -28,7 +28,7 @@
.. note::
- Functionality within this package requires that the ``__main__`` method be
+ 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
@@ -552,9 +552,9 @@
Return ``True`` if the queue is full, ``False`` otherwise. Because of
multithreading/multiprocessing semantics, this is not reliable.
- .. method:: put(item[, block[, timeout]])
+ .. method:: put(obj[, block[, timeout]])
- Put item into the queue. If the optional argument *block* is ``True``
+ Put obj into the queue. If the optional argument *block* is ``True``
(the default) and *timeout* is ``None`` (the default), block if necessary until
a free slot is available. If *timeout* is a positive number, it blocks at
most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
@@ -563,9 +563,9 @@
available, else raise the :exc:`Queue.Full` exception (*timeout* is
ignored in that case).
- .. method:: put_nowait(item)
+ .. method:: put_nowait(obj)
- Equivalent to ``put(item, False)``.
+ Equivalent to ``put(obj, False)``.
.. method:: get([block[, timeout]])
@@ -1602,7 +1602,7 @@
the process pool as separate tasks. The (approximate) size of these
chunks can be specified by setting *chunksize* to a positive integer.
- .. method:: map_async(func, iterable[, chunksize[, callback]])
+ .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]])
A variant of the :meth:`.map` method which returns a result object.
diff --git a/Doc/library/netrc.rst b/Doc/library/netrc.rst
index 8a2f1c6..323fd69 100644
--- a/Doc/library/netrc.rst
+++ b/Doc/library/netrc.rst
@@ -10,6 +10,10 @@
.. versionadded:: 1.5.2
+**Source code:** :source:`Lib/netrc.py`
+
+--------------
+
The :class:`netrc` class parses and encapsulates the netrc file format used by
the Unix :program:`ftp` program and other FTP clients.
diff --git a/Doc/library/nntplib.rst b/Doc/library/nntplib.rst
index 7a461b4..acbb7a5 100644
--- a/Doc/library/nntplib.rst
+++ b/Doc/library/nntplib.rst
@@ -10,6 +10,10 @@
pair: NNTP; protocol
single: Network News Transfer Protocol
+**Source code:** :source:`Lib/nntplib.py`
+
+--------------
+
This module defines the class :class:`NNTP` which implements the client side of
the NNTP protocol. It can be used to implement a news reader or poster, or
automated news processors. For more information on NNTP (Network News Transfer
diff --git a/Doc/library/numbers.rst b/Doc/library/numbers.rst
index a0a825f..f46e8ac 100644
--- a/Doc/library/numbers.rst
+++ b/Doc/library/numbers.rst
@@ -7,9 +7,9 @@
.. versionadded:: 2.6
-The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric abstract
-base classes which progressively define more operations. None of the types
-defined in this module can be instantiated.
+The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric
+:term:`abstract base classes <abstract base class>` which progressively define
+more operations. None of the types defined in this module can be instantiated.
.. class:: Number
diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst
index d4b121b..cb78b83 100644
--- a/Doc/library/optparse.rst
+++ b/Doc/library/optparse.rst
@@ -4,17 +4,18 @@
.. module:: optparse
:synopsis: Command-line option parsing library.
:deprecated:
+.. moduleauthor:: Greg Ward <gward@python.net>
+.. sectionauthor:: Greg Ward <gward@python.net>
+
+.. versionadded:: 2.3
.. deprecated:: 2.7
The :mod:`optparse` module is deprecated and will not be developed further;
development will continue with the :mod:`argparse` module.
-.. moduleauthor:: Greg Ward <gward@python.net>
+**Source code:** :source:`Lib/optparse.py`
-.. versionadded:: 2.3
-
-.. sectionauthor:: Greg Ward <gward@python.net>
-
+--------------
:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
@@ -657,8 +658,9 @@
.. method:: OptionParser.get_option_group(opt_str)
- Return, if defined, the :class:`OptionGroup` that has the title or the long
- description equals to *opt_str*
+ Return the :class:`OptionGroup` to which the short or long option
+ string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
+ there's no such :class:`OptionGroup`, return ``None``.
.. _optparse-printing-version-string:
diff --git a/Doc/library/os.path.rst b/Doc/library/os.path.rst
index 4867e8b..62bbdff 100644
--- a/Doc/library/os.path.rst
+++ b/Doc/library/os.path.rst
@@ -196,10 +196,11 @@
path, all previous components (on Windows, including the previous drive letter,
if there was one) are thrown away, and joining continues. The return value is
the concatenation of *path1*, and optionally *path2*, etc., with exactly one
- directory separator (``os.sep``) inserted between components, unless *path2* is
- empty. Note that on Windows, since there is a current directory for each drive,
- ``os.path.join("c:", "foo")`` represents a path relative to the current
- directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
+ directory separator (``os.sep``) following each non-empty part except the last.
+ (This means that an empty last part will result in a path that ends with a
+ separator.) Note that on Windows, since there is a current directory for
+ each drive, ``os.path.join("c:", "foo")`` represents a path relative to the
+ current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
.. function:: normcase(path)
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index b16fb1f..9968e6e 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -53,6 +53,13 @@
names have currently been registered: ``'posix'``, ``'nt'``,
``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``.
+ .. seealso::
+ :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives
+ system-dependent version information.
+
+ The :mod:`platform` module provides detailed checks for the
+ system's identity.
+
.. _os-procinfo:
@@ -916,7 +923,26 @@
Using :func:`access` to check if a user is authorized to e.g. open a file
before actually doing so using :func:`open` creates a security hole,
because the user might exploit the short time interval between checking
- and opening the file to manipulate it.
+ and opening the file to manipulate it. It's preferable to use :term:`EAFP`
+ techniques. For example::
+
+ if os.access("myfile", os.R_OK):
+ with open("myfile") as fp:
+ return fp.read()
+ return "some default data"
+
+ is better written as::
+
+ try:
+ fp = open("myfile")
+ except IOError as e:
+ if e.errno == errno.EACCESS:
+ return "some default data"
+ # Not a permission error.
+ raise
+ else:
+ with fp:
+ return fp.read()
.. note::
@@ -995,6 +1021,8 @@
* :data:`stat.UF_APPEND`
* :data:`stat.UF_OPAQUE`
* :data:`stat.UF_NOUNLINK`
+ * :data:`stat.UF_COMPRESSED`
+ * :data:`stat.UF_HIDDEN`
* :data:`stat.SF_ARCHIVED`
* :data:`stat.SF_IMMUTABLE`
* :data:`stat.SF_APPEND`
@@ -1367,11 +1395,12 @@
.. note::
- The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
- :attr:`st_ctime` members depends on the operating system and the file system.
- For example, on Windows systems using the FAT or FAT32 file systems,
- :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
- resolution. See your operating system documentation for details.
+ The exact meaning and resolution of the :attr:`st_atime`,
+ :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
+ system and the file system. For example, on Windows systems using the FAT
+ or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
+ :attr:`st_atime` has only 1-day resolution. See your operating system
+ documentation for details.
For backward compatibility, the return value of :func:`~os.stat` is also accessible
as a tuple of at least 10 integers giving the most important (and portable)
@@ -1644,8 +1673,9 @@
Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
behavior is to produce a core dump; on Windows, the process immediately returns
- an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
- to register a handler for :const:`SIGABRT` will behave differently.
+ an exit code of ``3``. Be aware that calling this function will not call the
+ Python signal handler registered for :const:`SIGABRT` with
+ :func:`signal.signal`.
Availability: Unix, Windows.
@@ -2022,7 +2052,9 @@
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
- and :func:`spawnvpe` are not available on Windows.
+ and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
+ :func:`spawnve` are not thread-safe on Windows; we advise you to use the
+ :mod:`subprocess` module instead.
.. versionadded:: 1.6
diff --git a/Doc/library/ossaudiodev.rst b/Doc/library/ossaudiodev.rst
index 37ead5d..848eca5 100644
--- a/Doc/library/ossaudiodev.rst
+++ b/Doc/library/ossaudiodev.rst
@@ -17,7 +17,7 @@
ALSA is in the standard kernel as of 2.5.x. Presumably if you
use ALSA, you'll have to make sure its OSS compatibility layer
is active to use ossaudiodev, but you're gonna need it for the vast
- majority of Linux audio apps anyways.
+ majority of Linux audio apps anyway.
Sounds like things are also complicated for other BSDs. In response
to my python-dev query, Thomas Wouters said:
diff --git a/Doc/library/pickletools.rst b/Doc/library/pickletools.rst
index ea16190..ce47c97 100644
--- a/Doc/library/pickletools.rst
+++ b/Doc/library/pickletools.rst
@@ -8,6 +8,10 @@
.. versionadded:: 2.3
+**Source code:** :source:`Lib/pickletools.py`
+
+--------------
+
This module contains various constants relating to the intimate details of the
:mod:`pickle` module, some lengthy comments about the implementation, and a few
useful functions for analyzing pickled data. The contents of this module are
diff --git a/Doc/library/pipes.rst b/Doc/library/pipes.rst
index 1f2b2ff..016a720 100644
--- a/Doc/library/pipes.rst
+++ b/Doc/library/pipes.rst
@@ -1,4 +1,3 @@
-
:mod:`pipes` --- Interface to shell pipelines
=============================================
@@ -7,6 +6,9 @@
:synopsis: A Python interface to Unix shell pipelines.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
+**Source code:** :source:`Lib/pipes.py`
+
+--------------
The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
--- a sequence of converters from one file to another.
diff --git a/Doc/library/pkgutil.rst b/Doc/library/pkgutil.rst
index 9e634d6..9971145 100644
--- a/Doc/library/pkgutil.rst
+++ b/Doc/library/pkgutil.rst
@@ -1,15 +1,18 @@
-
:mod:`pkgutil` --- Package extension utility
============================================
.. module:: pkgutil
:synopsis: Utilities for the import system.
+.. versionadded:: 2.3
+
+**Source code:** :source:`Lib/pkgutil.py`
+
+--------------
+
This module provides utilities for the import system, in particular package
support.
-.. versionadded:: 2.3
-
.. function:: extend_path(path, name)
@@ -187,3 +190,5 @@
If the package cannot be located or loaded, or it uses a :pep:`302` loader
which does not support :func:`get_data`, then ``None`` is returned.
+
+ .. versionadded:: 2.6
diff --git a/Doc/library/platform.rst b/Doc/library/platform.rst
index 7802422..0b78d49 100644
--- a/Doc/library/platform.rst
+++ b/Doc/library/platform.rst
@@ -9,6 +9,10 @@
.. versionadded:: 2.3
+**Source code:** :source:`Lib/platform.py`
+
+--------------
+
.. note::
Specific platforms listed alphabetically, with Linux included in the Unix
@@ -108,7 +112,7 @@
.. function:: python_implementation()
Returns a string identifying the Python implementation. Possible return values
- are: 'CPython', 'IronPython', 'Jython'.
+ are: 'CPython', 'IronPython', 'Jython', 'PyPy'.
.. versionadded:: 2.6
@@ -233,9 +237,6 @@
Entries which cannot be determined are set to ``''``. All tuple entries are
strings.
- Documentation for the underlying :cfunc:`gestalt` API is available online at
- http://www.rgaros.nl/gestalt/.
-
Unix Platforms
--------------
diff --git a/Doc/library/plistlib.rst b/Doc/library/plistlib.rst
index 309ddec..11268c2 100644
--- a/Doc/library/plistlib.rst
+++ b/Doc/library/plistlib.rst
@@ -15,6 +15,10 @@
pair: plist; file
single: property list
+**Source code:** :source:`Lib/plistlib.py`
+
+--------------
+
This module provides an interface for reading and writing the "property list"
XML files used mainly by Mac OS X.
diff --git a/Doc/library/poplib.rst b/Doc/library/poplib.rst
index e5f693d..8456304 100644
--- a/Doc/library/poplib.rst
+++ b/Doc/library/poplib.rst
@@ -1,4 +1,3 @@
-
:mod:`poplib` --- POP3 protocol client
======================================
@@ -9,6 +8,10 @@
.. index:: pair: POP3; protocol
+**Source code:** :source:`Lib/poplib.py`
+
+--------------
+
This module defines a class, :class:`POP3`, which encapsulates a connection to a
POP3 server and implements the protocol as defined in :rfc:`1725`. The
:class:`POP3` class supports both the minimal and optional command sets.
diff --git a/Doc/library/pprint.rst b/Doc/library/pprint.rst
index 7f13029..a0a7200 100644
--- a/Doc/library/pprint.rst
+++ b/Doc/library/pprint.rst
@@ -1,4 +1,3 @@
-
:mod:`pprint` --- Data pretty printer
=====================================
@@ -7,6 +6,9 @@
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/pprint.py`
+
+--------------
The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the interpreter.
@@ -28,10 +30,6 @@
.. versionchanged:: 2.6
Added support for :class:`set` and :class:`frozenset`.
-.. seealso::
-
- Latest version of the `pprint module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup>`_
The :mod:`pprint` module defines one class:
diff --git a/Doc/library/profile.rst b/Doc/library/profile.rst
index 1e2350f..236324d 100644
--- a/Doc/library/profile.rst
+++ b/Doc/library/profile.rst
@@ -1,4 +1,3 @@
-
.. _profile:
********************
@@ -10,29 +9,9 @@
.. module:: profile
:synopsis: Python source profiler.
-.. index:: single: InfoSeek Corporation
+**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py`
-Copyright © 1994, by InfoSeek Corporation, all rights reserved.
-
-Written by James Roskind. [#]_
-
-Permission to use, copy, modify, and distribute this Python software and its
-associated documentation for any purpose (subject to the restriction in the
-following sentence) without fee is hereby granted, provided that the above
-copyright notice appears in all copies, and that both that copyright notice and
-this permission notice appear in supporting documentation, and that the name of
-InfoSeek not be used in advertising or publicity pertaining to distribution of
-the software without specific, written prior permission. This permission is
-explicitly restricted to the copying and modification of the software to remain
-in Python, compiled Python, or other languages (such as C) wherein the modified
-or derived code is exclusively imported into a Python module.
-
-INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT
-SHALL INFOSEEK CORPORATION 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.
+--------------
.. _profiler-introduction:
@@ -65,7 +44,6 @@
:mod:`cProfile`. Adds significant overhead to profiled programs.
If you're trying to extend
the profiler in some way, the task might be easier with this module.
- Copyright © 1994, by InfoSeek Corporation.
.. versionchanged:: 2.4
Now also reports the time spent in calls to built-in functions and methods.
diff --git a/Doc/library/py_compile.rst b/Doc/library/py_compile.rst
index ca86143..66f015b 100644
--- a/Doc/library/py_compile.rst
+++ b/Doc/library/py_compile.rst
@@ -8,6 +8,10 @@
.. index:: pair: file; byte-code
+**Source code:** :source:`Lib/py_compile.py`
+
+--------------
+
The :mod:`py_compile` module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.
diff --git a/Doc/library/pyclbr.rst b/Doc/library/pyclbr.rst
index 36b46f4..2f81451 100644
--- a/Doc/library/pyclbr.rst
+++ b/Doc/library/pyclbr.rst
@@ -1,4 +1,3 @@
-
:mod:`pyclbr` --- Python class browser support
==============================================
@@ -6,6 +5,9 @@
:synopsis: Supports information extraction for a Python class browser.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/pyclbr.py`
+
+--------------
The :mod:`pyclbr` module can be used to determine some limited information
about the classes, methods and top-level functions defined in a module. The
@@ -43,7 +45,7 @@
The :class:`Class` objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data
-members:
+attributes:
.. attribute:: Class.module
@@ -87,7 +89,7 @@
----------------
The :class:`Function` objects used as values in the dictionary returned by
-:func:`readmodule_ex` provide the following data members:
+:func:`readmodule_ex` provide the following attributes:
.. attribute:: Function.module
diff --git a/Doc/library/pydoc.rst b/Doc/library/pydoc.rst
index e5f8fe2..8343452 100644
--- a/Doc/library/pydoc.rst
+++ b/Doc/library/pydoc.rst
@@ -1,4 +1,3 @@
-
:mod:`pydoc` --- Documentation generator and online help system
===============================================================
@@ -15,6 +14,10 @@
single: documentation; online
single: help; online
+**Source code:** :source:`Lib/pydoc.py`
+
+--------------
+
The :mod:`pydoc` module automatically generates documentation from Python
modules. The documentation can be presented as pages of text on the console,
served to a Web browser, or saved to HTML files.
diff --git a/Doc/library/queue.rst b/Doc/library/queue.rst
index a471bb0..36ff346 100644
--- a/Doc/library/queue.rst
+++ b/Doc/library/queue.rst
@@ -1,4 +1,4 @@
-:mod:`queue` --- A synchronized queue class
+:mod:`Queue` --- A synchronized queue class
===========================================
.. module:: Queue
@@ -9,6 +9,9 @@
:term:`2to3` tool will automatically adapt imports when converting your
sources to 3.0.
+**Source code:** :source:`Lib/Queue.py`
+
+--------------
The :mod:`Queue` module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
@@ -24,11 +27,6 @@
the entries are kept sorted (using the :mod:`heapq` module) and the
lowest valued entry is retrieved first.
-.. seealso::
-
- Latest version of the `queue module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/Queue.py?view=markup>`_.
-
The :mod:`Queue` module defines the following classes and exceptions:
.. class:: Queue(maxsize=0)
diff --git a/Doc/library/quopri.rst b/Doc/library/quopri.rst
index 87d70c3..67cbaba 100644
--- a/Doc/library/quopri.rst
+++ b/Doc/library/quopri.rst
@@ -1,4 +1,3 @@
-
:mod:`quopri` --- Encode and decode MIME quoted-printable data
==============================================================
@@ -10,6 +9,10 @@
pair: quoted-printable; encoding
single: MIME; quoted-printable encoding
+**Source code:** :source:`Lib/quopri.py`
+
+--------------
+
This module performs quoted-printable transport encoding and decoding, as
defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One:
Mechanisms for Specifying and Describing the Format of Internet Message Bodies".
@@ -18,11 +21,6 @@
:mod:`base64` module is more compact if there are many such characters, as when
sending a graphics file.
-.. seealso::
-
- Latest version of the `quopri module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/quopri.py?view=markup>`_
-
.. function:: decode(input, output[,header])
Decode the contents of the *input* file and write the resulting decoded binary
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
index 4306911..de98c04 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -1,19 +1,16 @@
-
:mod:`random` --- Generate pseudo-random numbers
================================================
.. module:: random
:synopsis: Generate pseudo-random numbers with various common distributions.
+**Source code:** :source:`Lib/random.py`
+
+--------------
This module implements pseudo-random number generators for various
distributions.
-.. seealso::
-
- Latest version of the `random module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/random.py?view=markup>`_
-
For integers, uniform selection from a range. For sequences, uniform selection
of a random element, a function to generate a random permutation of a list
in-place, and a function for random sampling without replacement.
@@ -199,6 +196,7 @@
The end-point value ``b`` may or may not be included in the range
depending on floating-point rounding in the equation ``a + (b-a) * random()``.
+
.. function:: triangular(low, high, mode)
Return a random floating point number *N* such that ``low <= N <= high`` and
@@ -229,6 +227,12 @@
Gamma distribution. (*Not* the gamma function!) Conditions on the
parameters are ``alpha > 0`` and ``beta > 0``.
+ The probability distribution function is::
+
+ x ** (alpha - 1) * math.exp(-x / beta)
+ pdf(x) = --------------------------------------
+ math.gamma(alpha) * beta ** alpha
+
.. function:: gauss(mu, sigma)
diff --git a/Doc/library/re.rst b/Doc/library/re.rst
index f789601..599e4d3 100644
--- a/Doc/library/re.rst
+++ b/Doc/library/re.rst
@@ -613,7 +613,7 @@
of *pattern* in *string* by the replacement *repl*. If the pattern isn't found,
*string* is returned unchanged. *repl* can be a string or a function; if it is
a string, any backslash escapes in it are processed. That is, ``\n`` is
- converted to a single newline character, ``\r`` is converted to a linefeed, and
+ converted to a single newline character, ``\r`` is converted to a carriage return, and
so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such
as ``\6``, are replaced with the substring matched by group 6 in the pattern.
For example:
diff --git a/Doc/library/repr.rst b/Doc/library/repr.rst
index 5bf5bf2..11e6ae2 100644
--- a/Doc/library/repr.rst
+++ b/Doc/library/repr.rst
@@ -1,4 +1,3 @@
-
:mod:`repr` --- Alternate :func:`repr` implementation
=====================================================
@@ -11,15 +10,14 @@
:term:`2to3` tool will automatically adapt imports when converting your
sources to 3.0.
+**Source code:** :source:`Lib/repr.py`
+
+--------------
+
The :mod:`repr` module provides a means for producing object representations
with limits on the size of the resulting strings. This is used in the Python
debugger and may be useful in other contexts as well.
-.. seealso::
-
- Latest version of the `repr module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/repr.py?view=markup>`_
-
This module provides a class, an instance, and a function:
@@ -49,7 +47,7 @@
Repr Objects
------------
-:class:`Repr` instances provide several members which can be used to provide
+:class:`Repr` instances provide several attributes which can be used to provide
size limits for the representations of different object types, and methods
which format specific object types.
diff --git a/Doc/library/rlcompleter.rst b/Doc/library/rlcompleter.rst
index 85a9d79..318b3ea 100644
--- a/Doc/library/rlcompleter.rst
+++ b/Doc/library/rlcompleter.rst
@@ -1,4 +1,3 @@
-
:mod:`rlcompleter` --- Completion function for GNU readline
===========================================================
@@ -6,6 +5,9 @@
:synopsis: Python identifier completion, suitable for the GNU readline library.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
+**Source code:** :source:`Lib/rlcompleter.py`
+
+--------------
The :mod:`rlcompleter` module defines a completion function suitable for the
:mod:`readline` module by completing valid Python identifiers and keywords.
diff --git a/Doc/library/runpy.rst b/Doc/library/runpy.rst
index 905c64b..31562fe 100644
--- a/Doc/library/runpy.rst
+++ b/Doc/library/runpy.rst
@@ -8,6 +8,10 @@
.. versionadded:: 2.5
+**Source code:** :source:`Lib/runpy.py`
+
+--------------
+
The :mod:`runpy` module is used to locate and run Python modules without
importing them first. Its main use is to implement the :option:`-m` command
line switch that allows scripts to be located using the Python module
diff --git a/Doc/library/sched.rst b/Doc/library/sched.rst
index 1efe47a..824df04 100644
--- a/Doc/library/sched.rst
+++ b/Doc/library/sched.rst
@@ -7,14 +7,13 @@
.. index:: single: event scheduling
+**Source code:** :source:`Lib/sched.py`
+
+--------------
+
The :mod:`sched` module defines a class which implements a general purpose event
scheduler:
-.. seealso::
-
- Latest version of the `sched module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/sched.py?view=markup>`_
-
.. class:: scheduler(timefunc, delayfunc)
The :class:`scheduler` class defines a generic interface to scheduling events.
diff --git a/Doc/library/shelve.rst b/Doc/library/shelve.rst
index 4f2d94b..7a70ff4 100644
--- a/Doc/library/shelve.rst
+++ b/Doc/library/shelve.rst
@@ -7,16 +7,16 @@
.. index:: module: pickle
+**Source code:** :source:`Lib/shelve.py`
+
+--------------
+
A "shelf" is a persistent, dictionary-like object. The difference with "dbm"
databases is that the values (not the keys!) in a shelf can be essentially
arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
This includes most class instances, recursive data types, and objects containing
lots of shared sub-objects. The keys are ordinary strings.
-.. seealso::
-
- Latest version of the `shelve module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/shelve.py?view=markup>`_
.. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])
diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst
index 0ae77c1..f462244 100644
--- a/Doc/library/shlex.rst
+++ b/Doc/library/shlex.rst
@@ -1,4 +1,3 @@
-
:mod:`shlex` --- Simple lexical analysis
========================================
@@ -12,6 +11,11 @@
.. versionadded:: 1.5.2
+**Source code:** :source:`Lib/shlex.py`
+
+--------------
+
+
The :class:`shlex` class makes it easy to write lexical analyzers for simple
syntaxes resembling that of the Unix shell. This will often be useful for
writing minilanguages, (for example, in run control files for Python
@@ -28,8 +32,8 @@
Split the string *s* using shell-like syntax. If *comments* is :const:`False`
(the default), the parsing of comments in the given string will be disabled
- (setting the :attr:`commenters` member of the :class:`shlex` instance to the
- empty string). This function operates in POSIX mode by default, but uses
+ (setting the :attr:`commenters` attribute of the :class:`shlex` instance to
+ the empty string). This function operates in POSIX mode by default, but uses
non-POSIX mode if the *posix* argument is false.
.. versionadded:: 2.3
@@ -53,7 +57,7 @@
:meth:`readline` methods, or a string (strings are accepted since Python 2.3).
If no argument is given, input will be taken from ``sys.stdin``. The second
optional argument is a filename string, which sets the initial value of the
- :attr:`infile` member. If the *instream* argument is omitted or equal to
+ :attr:`infile` attribute. If the *instream* argument is omitted or equal to
``sys.stdin``, this second argument defaults to "stdin". The *posix* argument
was introduced in Python 2.3, and defines the operational mode. When *posix* is
not true (default), the :class:`shlex` instance will operate in compatibility
@@ -221,8 +225,8 @@
.. attribute:: shlex.source
- This member is ``None`` by default. If you assign a string to it, that string
- will be recognized as a lexical-level inclusion request similar to the
+ This attribute is ``None`` by default. If you assign a string to it, that
+ string will be recognized as a lexical-level inclusion request similar to the
``source`` keyword in various shells. That is, the immediately following token
will opened as a filename and input taken from that stream until EOF, at which
point the :meth:`close` method of that stream will be called and the input
@@ -232,7 +236,7 @@
.. attribute:: shlex.debug
- If this member is numeric and ``1`` or more, a :class:`shlex` instance will
+ If this attribute is numeric and ``1`` or more, a :class:`shlex` instance will
print verbose progress output on its behavior. If you need to use this, you can
read the module source code to learn the details.
diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst
index 1b160d8..3126965 100644
--- a/Doc/library/shutil.rst
+++ b/Doc/library/shutil.rst
@@ -1,4 +1,3 @@
-
:mod:`shutil` --- High-level file operations
============================================
@@ -11,16 +10,15 @@
single: file; copying
single: copying files
+**Source code:** :source:`Lib/shutil.py`
+
+--------------
+
The :mod:`shutil` module offers a number of high-level operations on files and
collections of files. In particular, functions are provided which support file
copying and removal. For operations on individual files, see also the
:mod:`os` module.
-.. seealso::
-
- Latest version of the `shutil module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/shutil.py?view=markup>`_
-
.. warning::
Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
@@ -105,8 +103,9 @@
:func:`copy2`.
If *symlinks* is true, symbolic links in the source tree are represented as
- symbolic links in the new tree; if false or omitted, the contents of the
- linked files are copied to the new tree.
+ symbolic links in the new tree, but the metadata of the original links is NOT
+ copied; if false or omitted, the contents and metadata of the linked files
+ are copied to the new tree.
If *ignore* is given, it must be a callable that will receive as its
arguments the directory being visited by :func:`copytree`, and a list of its
@@ -161,22 +160,31 @@
.. function:: move(src, dst)
- Recursively move a file or directory to another location.
+ Recursively move a file or directory (*src*) to another location (*dst*).
- If the destination is on the current filesystem, then simply use rename.
- Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
+ 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 on the current filesystem, then :func:`os.rename` is
+ used. Otherwise, *src* is copied (using :func:`copy2`) to *dst* and then
+ removed.
.. versionadded:: 2.3
.. exception:: Error
- This exception collects exceptions that raised during a multi-file operation. For
- :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*,
- *dstname*, *exception*).
+ This exception collects exceptions that are raised during a multi-file
+ operation. For :func:`copytree`, the exception argument is a list of 3-tuples
+ (*srcname*, *dstname*, *exception*).
.. versionadded:: 2.3
+
.. _shutil-example:
copytree example
@@ -270,12 +278,14 @@
*owner* and *group* are used when creating a tar archive. By default,
uses the current owner and group.
+ *logger* is an instance of :class:`logging.Logger`.
+
.. versionadded:: 2.7
.. function:: get_archive_formats()
- Returns a list of supported formats for archiving.
+ Return a list of supported formats for archiving.
Each element of the returned sequence is a tuple ``(name, description)``
By default :mod:`shutil` provides these formats:
@@ -293,7 +303,7 @@
.. function:: register_archive_format(name, function, [extra_args, [description]])
- Registers an archiver for the format *name*. *function* is a callable that
+ Register an archiver for the format *name*. *function* is a callable that
will be used to invoke the archiver.
If given, *extra_args* is a sequence of ``(name, value)`` that will be
diff --git a/Doc/library/simplexmlrpcserver.rst b/Doc/library/simplexmlrpcserver.rst
index c0819bf..3618728 100644
--- a/Doc/library/simplexmlrpcserver.rst
+++ b/Doc/library/simplexmlrpcserver.rst
@@ -14,6 +14,10 @@
.. versionadded:: 2.2
+**Source code:** :source:`Lib/SimpleXMLRPCServer.py`
+
+--------------
+
The :mod:`SimpleXMLRPCServer` module provides a basic server framework for
XML-RPC servers written in Python. Servers can either be free standing, using
:class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using
diff --git a/Doc/library/site.rst b/Doc/library/site.rst
index 6ad156e..c0fafed 100644
--- a/Doc/library/site.rst
+++ b/Doc/library/site.rst
@@ -1,17 +1,22 @@
-
:mod:`site` --- Site-specific configuration hook
================================================
.. module:: site
- :synopsis: A standard way to reference site-specific modules.
+ :synopsis: Module responsible for site-specific configuration.
+**Source code:** :source:`Lib/site.py`
+
+--------------
+
+.. highlightlang:: none
**This module is automatically imported during initialization.** The automatic
import can be suppressed using the interpreter's :option:`-S` option.
.. index:: triple: module; search; path
-Importing this module will append site-specific paths to the module search path.
+Importing this module will append site-specific paths to the module search path
+and add a few builtins.
.. index::
pair: site-python; directory
@@ -26,11 +31,11 @@
if it refers to an existing directory, and if so, adds it to ``sys.path`` and
also inspects the newly added path for configuration files.
-A path configuration file is a file whose name has the form :file:`package.pth`
+A path configuration file is a file whose name has the form :file:`{name}.pth`
and exists in one of the four directories mentioned above; its contents are
additional items (one per line) to be added to ``sys.path``. Non-existing items
-are never added to ``sys.path``, but no check is made that the item refers to a
-directory (rather than a file). No item is added to ``sys.path`` more than
+are never added to ``sys.path``, and no check is made that the item refers to a
+directory rather than a file. No item is added to ``sys.path`` more than
once. Blank lines and lines beginning with ``#`` are skipped. Lines starting
with ``import`` (followed by space or tab) are executed.
@@ -43,8 +48,7 @@
For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to
:file:`/usr/local`. The Python X.Y library is then installed in
-:file:`/usr/local/lib/python{X.Y}` (where only the first three characters of
-``sys.version`` are used to form the installation path name). Suppose this has
+:file:`/usr/local/lib/python{X.Y}`. Suppose this has
a subdirectory :file:`/usr/local/lib/python{X.Y}/site-packages` with three
subsubdirectories, :file:`foo`, :file:`bar` and :file:`spam`, and two path
configuration files, :file:`foo.pth` and :file:`bar.pth`. Assume
@@ -77,86 +81,132 @@
After these path manipulations, an attempt is made to import a module named
:mod:`sitecustomize`, which can perform arbitrary site-specific customizations.
-If this import fails with an :exc:`ImportError` exception, it is silently
-ignored.
+It is typically created by a system administrator in the site-packages
+directory. If this import fails with an :exc:`ImportError` exception, it is
+silently ignored.
-.. index:: module: sitecustomize
+.. index:: module: usercustomize
+
+After this, an attempt is made to import a module named :mod:`usercustomize`,
+which can perform arbitrary user-specific customizations, if
+:data:`ENABLE_USER_SITE` is true. This file is intended to be created in the
+user site-packages directory (see below), which is part of ``sys.path`` unless
+disabled by :option:`-s`. An :exc:`ImportError` will be silently ignored.
Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` are
empty, and the path manipulations are skipped; however the import of
-:mod:`sitecustomize` is still attempted.
+:mod:`sitecustomize` and :mod:`usercustomize` is still attempted.
.. data:: PREFIXES
- A list of prefixes for site package directories
+ A list of prefixes for site-packages directories.
.. versionadded:: 2.6
.. data:: ENABLE_USER_SITE
- Flag showing the status of the user site directory. True means the
- user site directory is enabled and added to sys.path. When the flag
- is None the user site directory is disabled for security reasons.
+ Flag showing the status of the user site-packages directory. ``True`` means
+ that it is enabled and was added to ``sys.path``. ``False`` means that it
+ was disabled by user request (with :option:`-s` or
+ :envvar:`PYTHONNOUSERSITE`). ``None`` means it was disabled for security
+ reasons (mismatch between user or group id and effective id) or by an
+ administrator.
.. versionadded:: 2.6
.. data:: USER_SITE
- Path to the user site directory for the current Python version or None
+ Path to the user site-packages for the running Python. Can be ``None`` if
+ :func:`getusersitepackages` hasn't been called yet. Default value is
+ :file:`~/.local/lib/python{X.Y}/site-packages` for UNIX and non-framework Mac
+ OS X builds, :file:`~/Library/Python/{X.Y}/lib/python/site-packages` for Mac
+ framework builds, and :file:`{%APPDATA%}\\Python\\Python{XY}\\site-packages`
+ on Windows. This directory is a site directory, which means that
+ :file:`.pth` files in it will be processed.
.. versionadded:: 2.6
.. data:: USER_BASE
- Path to the base directory for user site directories
-
- .. versionadded:: 2.6
-
-
-.. envvar:: PYTHONNOUSERSITE
-
- .. versionadded:: 2.6
-
-
-.. envvar:: PYTHONUSERBASE
+ Path to the base directory for the user site-packages. Can be ``None`` if
+ :func:`getuserbase` hasn't been called yet. Default value is
+ :file:`~/.local` for UNIX and Mac OS X non-framework builds,
+ :file:`~/Library/Python/{X.Y}` for Mac framework builds, and
+ :file:`{%APPDATA%}\\Python` for Windows. This value is used by Distutils to
+ compute the installation directories for scripts, data files, Python modules,
+ etc. for the :ref:`user installation scheme <inst-alt-install-user>`. See
+ also :envvar:`PYTHONUSERBASE`.
.. versionadded:: 2.6
.. function:: addsitedir(sitedir, known_paths=None)
- Adds a directory to sys.path and processes its pth files.
+ Add a directory to sys.path and process its :file:`.pth` files. Typically
+ used in :mod:`sitecustomize` or :mod:`usercustomize` (see above).
+
.. function:: getsitepackages()
- Returns a list containing all global site-packages directories
- (and possibly site-python).
+ Return a list containing all global site-packages directories (and possibly
+ site-python).
.. versionadded:: 2.7
+
.. function:: getuserbase()
- Returns the "user base" directory path.
-
- The "user base" directory can be used to store data. If the global
- variable ``USER_BASE`` is not initialized yet, this function will also set
- it.
+ Return the path of the user base directory, :data:`USER_BASE`. If it is not
+ initialized yet, this function will also set it, respecting
+ :envvar:`PYTHONUSERBASE`.
.. versionadded:: 2.7
+
.. function:: getusersitepackages()
- Returns the user-specific site-packages directory path.
-
- If the global variable ``USER_SITE`` is not initialized yet, this
- function will also set it.
+ Return the path of the user-specific site-packages directory,
+ :data:`USER_SITE`. If it is not initialized yet, this function will also set
+ it, respecting :envvar:`PYTHONNOUSERSITE` and :data:`USER_BASE`.
.. versionadded:: 2.7
-.. XXX Update documentation
-.. XXX document python -m site --user-base --user-site
+The :mod:`site` module also provides a way to get the user directories from the
+command line:
+
+.. code-block:: sh
+
+ $ python3 -m site --user-site
+ /home/user/.local/lib/python3.3/site-packages
+
+.. program:: site
+
+If it is called without arguments, it will print the contents of
+:data:`sys.path` on the standard output, followed by the value of
+:data:`USER_BASE` and whether the directory exists, then the same thing for
+:data:`USER_SITE`, and finally the value of :data:`ENABLE_USER_SITE`.
+
+.. cmdoption:: --user-base
+
+ Print the path to the user base directory.
+
+.. cmdoption:: --user-site
+
+ Print the path to the user site-packages directory.
+
+If both options are given, user base and user site will be printed (always in
+this order), separated by :data:`os.pathsep`.
+
+If any option is given, the script will exit with one of these values: ``O`` if
+the user site-packages directory is enabled, ``1`` if it was disabled by the
+user, ``2`` if it is disabled for security reasons or by an administrator, and a
+value greater than 2 if there is an error.
+
+.. seealso::
+
+ :pep:`370` -- Per user site-packages directory
diff --git a/Doc/library/smtpd.rst b/Doc/library/smtpd.rst
index 2767516..ebb0b30 100644
--- a/Doc/library/smtpd.rst
+++ b/Doc/library/smtpd.rst
@@ -7,8 +7,9 @@
.. moduleauthor:: Barry Warsaw <barry@zope.com>
.. sectionauthor:: Moshe Zadka <moshez@moshez.org>
+**Source code:** :source:`Lib/smtpd.py`
-
+--------------
This module offers several classes to implement SMTP servers. One is a generic
do-nothing implementation, which can be overridden, while the other two offer
diff --git a/Doc/library/smtplib.rst b/Doc/library/smtplib.rst
index d59ebf7..b0b58e8 100644
--- a/Doc/library/smtplib.rst
+++ b/Doc/library/smtplib.rst
@@ -1,4 +1,3 @@
-
:mod:`smtplib` --- SMTP protocol client
=======================================
@@ -11,6 +10,10 @@
pair: SMTP; protocol
single: Simple Mail Transfer Protocol
+**Source code:** :source:`Lib/smtplib.py`
+
+--------------
+
The :mod:`smtplib` module defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For
details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
diff --git a/Doc/library/sndhdr.rst b/Doc/library/sndhdr.rst
index 01a3917..f36df68 100644
--- a/Doc/library/sndhdr.rst
+++ b/Doc/library/sndhdr.rst
@@ -1,4 +1,3 @@
-
:mod:`sndhdr` --- Determine type of sound file
==============================================
@@ -11,6 +10,10 @@
single: A-LAW
single: u-LAW
+**Source code:** :source:`Lib/sndhdr.py`
+
+--------------
+
The :mod:`sndhdr` provides utility functions which attempt to determine the type
of sound data which is in a file. When these functions are able to determine
what type of sound data is stored in a file, they return a tuple ``(type,
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
index 96152f9..3fce587 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -488,7 +488,7 @@
.. function:: getdefaulttimeout()
- Return the default timeout in floating seconds for new socket objects. A value
+ Return the default timeout in seconds (float) for new socket objects. A value
of ``None`` indicates that new socket objects have no timeout. When the socket
module is first imported, the default is ``None``.
@@ -497,7 +497,7 @@
.. function:: setdefaulttimeout(timeout)
- Set the default timeout in floating seconds for new socket objects. A value of
+ Set the default timeout in seconds (float) for new socket objects. A value of
``None`` indicates that new socket objects have no timeout. When the socket
module is first imported, the default is ``None``.
@@ -644,8 +644,8 @@
.. method:: socket.listen(backlog)
Listen for connections made to the socket. The *backlog* argument specifies the
- maximum number of queued connections and should be at least 1; the maximum value
- is system-dependent (usually 5).
+ maximum number of queued connections and should be at least 0; the maximum value
+ is system-dependent (usually 5), the minimum value is forced to 0.
.. method:: socket.makefile([mode[, bufsize]])
@@ -766,7 +766,7 @@
.. method:: socket.gettimeout()
- Return the timeout in floating seconds associated with socket operations, or
+ Return the timeout in seconds (float) associated with socket operations, or
``None`` if no timeout is set. This reflects the last call to
:meth:`setblocking` or :meth:`settimeout`.
@@ -989,3 +989,22 @@
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
+
+
+Running an example several times with too small delay between executions, could
+lead to this error::
+
+ socket.error: [Errno 98] Address already in use
+
+This is because the previous execution has left the socket in a ``TIME_WAIT``
+state, and can't be immediately reused.
+
+There is a :mod:`socket` flag to set, in order to prevent this,
+:data:`socket.SO_REUSEADDR`::
+
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind((HOST, PORT))
+
+the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in
+``TIME_WAIT`` state, without waiting for its natural timeout to expire.
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index fce216e..4c48267 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -1,4 +1,3 @@
-
:mod:`SocketServer` --- A framework for network servers
=======================================================
@@ -11,6 +10,9 @@
Python 3.0. The :term:`2to3` tool will automatically adapt imports when
converting your sources to 3.0.
+**Source code:** :source:`Lib/SocketServer.py`
+
+--------------
The :mod:`SocketServer` module simplifies the task of writing network servers.
@@ -85,7 +87,7 @@
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
The mix-in class must come first, since it overrides a method defined in
-:class:`UDPServer`. Setting the various member variables also changes the
+:class:`UDPServer`. Setting the various attributes also change the
behavior of the underlying server mechanism.
To implement a service, you must derive a class from :class:`BaseRequestHandler`
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index 59ed097..3ef108c 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -378,6 +378,8 @@
.. literalinclude:: ../includes/sqlite3/load_extension.py
+ Loadable extensions are disabled by default. See [#f1]_
+
.. method:: Connection.load_extension(path)
.. versionadded:: 2.7
@@ -386,6 +388,8 @@
enable extension loading with :meth:`enable_load_extension` before you can
use this routine.
+ Loadable extensions are disabled by default. See [#f1]_
+
.. attribute:: Connection.row_factory
You can change this attribute to a callable that accepts the cursor and the
@@ -600,42 +604,42 @@
Let's assume we initialize a table as in the example given above::
- conn = sqlite3.connect(":memory:")
- c = conn.cursor()
- c.execute('''create table stocks
- (date text, trans text, symbol text,
- qty real, price real)''')
- c.execute("""insert into stocks
- values ('2006-01-05','BUY','RHAT',100,35.14)""")
- conn.commit()
- c.close()
+ conn = sqlite3.connect(":memory:")
+ c = conn.cursor()
+ c.execute('''create table stocks
+ (date text, trans text, symbol text,
+ qty real, price real)''')
+ c.execute("""insert into stocks
+ values ('2006-01-05','BUY','RHAT',100,35.14)""")
+ conn.commit()
+ c.close()
Now we plug :class:`Row` in::
- >>> conn.row_factory = sqlite3.Row
- >>> c = conn.cursor()
- >>> c.execute('select * from stocks')
- <sqlite3.Cursor object at 0x7f4e7dd8fa80>
- >>> r = c.fetchone()
- >>> type(r)
- <type 'sqlite3.Row'>
- >>> r
- (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
- >>> len(r)
- 5
- >>> r[2]
- u'RHAT'
- >>> r.keys()
- ['date', 'trans', 'symbol', 'qty', 'price']
- >>> r['qty']
- 100.0
- >>> for member in r: print member
- ...
- 2006-01-05
- BUY
- RHAT
- 100.0
- 35.14
+ >>> conn.row_factory = sqlite3.Row
+ >>> c = conn.cursor()
+ >>> c.execute('select * from stocks')
+ <sqlite3.Cursor object at 0x7f4e7dd8fa80>
+ >>> r = c.fetchone()
+ >>> type(r)
+ <type 'sqlite3.Row'>
+ >>> r
+ (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
+ >>> len(r)
+ 5
+ >>> r[2]
+ u'RHAT'
+ >>> r.keys()
+ ['date', 'trans', 'symbol', 'qty', 'price']
+ >>> r['qty']
+ 100.0
+ >>> for member in r: print member
+ ...
+ 2006-01-05
+ BUY
+ RHAT
+ 100.0
+ 35.14
.. _sqlite3-types:
@@ -893,3 +897,12 @@
The only exception is calling the :meth:`~Connection.interrupt` method, which
only makes sense to call from a different thread.
+
+.. rubric:: Footnotes
+
+.. [#f1] The sqlite3 module is not built with loadable extension support by
+ default, because some platforms (notably Mac OS X) have SQLite libraries
+ which are compiled without this feature. To get loadable extension support,
+ you must modify setup.py and remove the line that sets
+ SQLITE_OMIT_LOAD_EXTENSION.
+
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index a7e78bd..9b09894 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -5,9 +5,6 @@
:synopsis: TLS/SSL wrapper for socket objects
.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
-
-.. versionadded:: 2.6
-
.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
@@ -15,6 +12,12 @@
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
+.. versionadded:: 2.6
+
+**Source code:** :source:`Lib/ssl.py`
+
+--------------
+
This module provides access to Transport Layer Security (often known as "Secure
Sockets Layer") encryption and peer authentication facilities for network
sockets, both client-side and server-side. This module uses the OpenSSL
@@ -237,6 +240,9 @@
Selects SSL version 2 as the channel encryption protocol.
+ This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
+ flag.
+
.. warning::
SSL version 2 is insecure. Its use is highly discouraged.
@@ -616,8 +622,8 @@
Class :class:`socket.socket`
Documentation of underlying :mod:`socket` class
- `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
- Frederick J. Hirsch
+ `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
+ Debby Koren
`RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
Steve Kent
diff --git a/Doc/library/stat.rst b/Doc/library/stat.rst
index 417ba8d..8fd90da 100644
--- a/Doc/library/stat.rst
+++ b/Doc/library/stat.rst
@@ -1,4 +1,3 @@
-
:mod:`stat` --- Interpreting :func:`stat` results
=================================================
@@ -6,6 +5,9 @@
:synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
.. sectionauthor:: Skip Montanaro <skip@automatrix.com>
+**Source code:** :source:`Lib/stat.py`
+
+--------------
The :mod:`stat` module defines constants and functions for interpreting the
results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they
@@ -84,7 +86,7 @@
for f in os.listdir(top):
pathname = os.path.join(top, f)
- mode = os.stat(pathname)[ST_MODE]
+ mode = os.stat(pathname).st_mode
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
@@ -306,11 +308,19 @@
.. data:: UF_OPAQUE
- The file may not be renamed or deleted.
+ The directory is opaque when viewed through a union stack.
.. data:: UF_NOUNLINK
- The directory is opaque when viewed through a union stack.
+ The file may not be renamed or deleted.
+
+.. data:: UF_COMPRESSED
+
+ The file is stored compressed (Mac OS X 10.6+).
+
+.. data:: UF_HIDDEN
+
+ The file should not be displayed in a GUI (Mac OS X 10.5+).
.. data:: SF_ARCHIVED
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index da5db1d..30faddb 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -63,7 +63,7 @@
* instances of user-defined classes, if the class defines a :meth:`__nonzero__`
or :meth:`__len__` method, when that method returns the integer zero or
- :class:`bool` value ``False``. [#]_
+ :class:`bool` value ``False``. [1]_
.. index:: single: true
@@ -277,7 +277,7 @@
operands of different numeric types, the operand with the "narrower" type is
widened to that of the other, where plain integer is narrower than long integer
is narrower than floating point is narrower than complex. Comparisons between
-numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
+numbers of mixed type use the same rule. [2]_ The constructors :func:`int`,
:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
of a specific type.
@@ -460,6 +460,9 @@
Additional Methods on Integer Types
-----------------------------------
+The integer types implement the :class:`numbers.Integral` :term:`abstract base
+class`. In addition, they provide one more method:
+
.. method:: int.bit_length()
.. method:: long.bit_length()
@@ -491,7 +494,8 @@
Additional Methods on Float
---------------------------
-The float type has some additional methods.
+The float type implements the :class:`numbers.Real` :term:`abstract base
+class`. float also has the following additional methods.
.. method:: float.as_integer_ratio()
@@ -705,7 +709,7 @@
Most sequence types support the following operations. The ``in`` and ``not in``
operations have the same priorities as the comparison operations. The ``+`` and
``*`` operations have the same priority as the corresponding numeric operations.
-[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
+[3]_ Additional methods are provided for :ref:`typesseq-mutable`.
This table lists the sequence operations sorted in ascending priority
(operations in the same box have the same priority). In the table, *s* and *t*
@@ -940,6 +944,15 @@
*start* and *end* are interpreted as in slice notation. Return ``-1`` if
*sub* is not found.
+ .. note::
+
+ The :meth:`~str.find` method should be used only if you need to know the
+ position of *sub*. To check if *sub* is a substring or not, use the
+ :keyword:`in` operator::
+
+ >>> 'Py' in 'Python'
+ True
+
.. method:: str.format(*args, **kwargs)
@@ -994,7 +1007,7 @@
.. method:: str.islower()
- Return true if all cased characters in the string are lowercase and there is at
+ Return true if all cased characters [4]_ in the string are lowercase and there is at
least one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
@@ -1019,7 +1032,7 @@
.. method:: str.isupper()
- Return true if all cased characters in the string are uppercase and there is at
+ Return true if all cased characters [4]_ in the string are uppercase and there is at
least one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
@@ -1044,7 +1057,8 @@
.. method:: str.lower()
- Return a copy of the string converted to lowercase.
+ Return a copy of the string with all the cased characters [4]_ converted to
+ lowercase.
For 8-bit strings, this method is locale-dependent.
@@ -1267,7 +1281,10 @@
.. method:: str.upper()
- Return a copy of the string converted to uppercase.
+ Return a copy of the string with all the cased characters [4]_ converted to
+ uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s``
+ contains uncased characters or if the Unicode category of the resulting
+ character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).
For 8-bit strings, this method is locale-dependent.
@@ -1323,7 +1340,7 @@
the result will also be a Unicode object.
If *format* requires a single argument, *values* may be a single non-tuple
-object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
+object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
items specified by the format string, or a single mapping object (for example, a
dictionary).
@@ -2389,7 +2406,7 @@
.. method:: file.readline([size])
Read one entire line from the file. A trailing newline character is kept in
- the string (but may be absent when a file ends with an incomplete line). [#]_
+ the string (but may be absent when a file ends with an incomplete line). [6]_
If the *size* argument is present and non-negative, it is a maximum byte
count (including the trailing newline) and an incomplete line may be
returned. When *size* is not 0, an empty string is returned *only* when EOF
@@ -2774,7 +2791,7 @@
foo`` does not require a module object named *foo* to exist, rather it requires
an (external) *definition* for a module named *foo* somewhere.)
-A special member of every module is :attr:`__dict__`. This is the dictionary
+A special attribute of every module is :attr:`__dict__`. This is the dictionary
containing the module's symbol table. Modifying this dictionary will actually
change the module's symbol table, but direct assignment to the :attr:`__dict__`
attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
@@ -2917,7 +2934,18 @@
supports no special operations. There is exactly one ellipsis object, named
:const:`Ellipsis` (a built-in name).
-It is written as ``Ellipsis``.
+It is written as ``Ellipsis``. When in a subscript, it can also be written as
+``...``, for example ``seq[...]``.
+
+
+The NotImplemented Object
+-------------------------
+
+This object is returned from comparisons and binary operations when they are
+asked to operate on types they don't support. See :ref:`comparisons` for more
+information.
+
+It is written as ``NotImplemented``.
Boolean Values
@@ -3020,18 +3048,21 @@
.. rubric:: Footnotes
-.. [#] Additional information on these special methods may be found in the Python
+.. [1] Additional information on these special methods may be found in the Python
Reference Manual (:ref:`customization`).
-.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
+.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
similarly for tuples.
-.. [#] They must have since the parser can't tell the type of the operands.
+.. [3] They must have since the parser can't tell the type of the operands.
-.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
+.. [4] Cased characters are those with general category property being one of
+ "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
+
+.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
element is the tuple to be formatted.
-.. [#] The advantage of leaving the newline on is that returning an empty string is
+.. [6] The advantage of leaving the newline on is that returning an empty string is
then an unambiguous EOF indication. It is also possible (in cases where it
might matter, for example, if you want to make an exact copy of a file while
scanning its lines) to tell whether the last line of a file ended in a newline
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 59ac116..20fcae9 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -7,6 +7,10 @@
.. index:: module: re
+**Source code:** :source:`Lib/string.py`
+
+--------------
+
The :mod:`string` module contains a number of useful constants and
classes, as well as some deprecated legacy functions that are also
available as methods on strings. In addition, Python's built-in string
@@ -17,12 +21,6 @@
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.
-.. seealso::
-
- Latest version of the `string module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/string.py?view=markup>`_
-
-
String constants
----------------
@@ -250,6 +248,8 @@
it refers to a named keyword argument. If the numerical arg_names in a format string
are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
and the numbers 0, 1, 2, ... will be automatically inserted in that order.
+Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
+dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
The *arg_name* can be followed by any number of index or
attribute expressions. An expression of the form ``'.name'`` selects the named
attribute using :func:`getattr`, while an expression of the form ``'[index]'``
@@ -729,9 +729,9 @@
to parse template strings. To do this, you can override these class attributes:
* *delimiter* -- This is the literal string describing a placeholder introducing
- delimiter. The default value ``$``. Note that this should *not* be a regular
- expression, as the implementation will call :meth:`re.escape` on this string as
- needed.
+ delimiter. The default value is ``$``. Note that this should *not* be a
+ regular expression, as the implementation will call :meth:`re.escape` on this
+ string as needed.
* *idpattern* -- This is the regular expression describing the pattern for
non-braced placeholders (the braces will be added automatically as
diff --git a/Doc/library/struct.rst b/Doc/library/struct.rst
index 0b8052c..817c570 100644
--- a/Doc/library/struct.rst
+++ b/Doc/library/struct.rst
@@ -22,8 +22,8 @@
alignment is taken into account when unpacking. This behavior is chosen so
that the bytes of a packed struct correspond exactly to the layout in memory
of the corresponding C struct. To handle platform-independent data formats
- or omit implicit pad bytes, use `standard` size and alignment instead of
- `native` size and alignment: see :ref:`struct-alignment` for details.
+ or omit implicit pad bytes, use ``standard`` size and alignment instead of
+ ``native`` size and alignment: see :ref:`struct-alignment` for details.
Functions and Exceptions
------------------------
@@ -257,10 +257,11 @@
For the ``'s'`` format character, the count is interpreted as the size of the
string, not a repeat count like for the other format characters; for example,
``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
-For packing, the string is truncated or padded with null bytes as appropriate to
-make it fit. For unpacking, the resulting string always has exactly the
-specified number of bytes. As a special case, ``'0s'`` means a single, empty
-string (while ``'0c'`` means 0 characters).
+If a count is not given, it defaults to 1. For packing, the string is
+truncated or padded with null bytes as appropriate to make it fit. For
+unpacking, the resulting string always has exactly the specified number of
+bytes. As a special case, ``'0s'`` means a single, empty string (while
+``'0c'`` means 0 characters).
The ``'p'`` format character encodes a "Pascal string", meaning a short
variable-length string stored in a *fixed number of bytes*, given by the count.
@@ -314,7 +315,7 @@
>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
- >>> Student._make(unpack('<10sHHb', s))
+ >>> Student._make(unpack('<10sHHb', record))
Student(name='raymond ', serialnum=4658, school=264, gradelevel=8)
The ordering of format characters may have an impact on size since the padding
diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst
index e92847d..997165a 100644
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -178,9 +178,10 @@
:attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
communicate() method.
- The *startupinfo* and *creationflags*, if given, will be passed to the
- underlying CreateProcess() function. They can specify things such as appearance
- of the main window and priority for the new process. (Windows only)
+ If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
+ passed to the underlying ``CreateProcess`` function.
+ *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
+ :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
.. data:: PIPE
@@ -413,6 +414,110 @@
``N`` (Unix only).
+Windows Popen Helpers
+---------------------
+
+The :class:`STARTUPINFO` class and following constants are only available
+on Windows.
+
+.. class:: STARTUPINFO()
+
+ Partial support of the Windows
+ `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
+ structure is used for :class:`Popen` creation.
+
+ .. attribute:: dwFlags
+
+ A bit field that determines whether certain :class:`STARTUPINFO`
+ attributes are used when the process creates a window. ::
+
+ si = subprocess.STARTUPINFO()
+ si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
+
+ .. attribute:: hStdInput
+
+ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
+ is the standard input handle for the process. If
+ :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
+ input is the keyboard buffer.
+
+ .. attribute:: hStdOutput
+
+ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
+ is the standard output handle for the process. Otherwise, this attribute
+ is ignored and the default for standard output is the console window's
+ buffer.
+
+ .. attribute:: hStdError
+
+ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
+ is the standard error handle for the process. Otherwise, this attribute is
+ ignored and the default for standard error is the console window's buffer.
+
+ .. attribute:: wShowWindow
+
+ If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
+ can be any of the values that can be specified in the ``nCmdShow``
+ parameter for the
+ `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
+ function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
+ ignored.
+
+ :data:`SW_HIDE` is provided for this attribute. It is used when
+ :class:`Popen` is called with ``shell=True``.
+
+
+Constants
+^^^^^^^^^
+
+The :mod:`subprocess` module exposes the following constants.
+
+.. data:: STD_INPUT_HANDLE
+
+ The standard input device. Initially, this is the console input buffer,
+ ``CONIN$``.
+
+.. data:: STD_OUTPUT_HANDLE
+
+ The standard output device. Initially, this is the active console screen
+ buffer, ``CONOUT$``.
+
+.. data:: STD_ERROR_HANDLE
+
+ The standard error device. Initially, this is the active console screen
+ buffer, ``CONOUT$``.
+
+.. data:: SW_HIDE
+
+ Hides the window. Another window will be activated.
+
+.. data:: STARTF_USESTDHANDLES
+
+ Specifies that the :attr:`STARTUPINFO.hStdInput`,
+ :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
+ contain additional information.
+
+.. data:: STARTF_USESHOWWINDOW
+
+ Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
+ additional information.
+
+.. data:: CREATE_NEW_CONSOLE
+
+ The new process has a new console, instead of inheriting its parent's
+ console (the default).
+
+ This flag is always set when :class:`Popen` is created with ``shell=True``.
+
+.. data:: CREATE_NEW_PROCESS_GROUP
+
+ A :class:`Popen` ``creationflags`` parameter to specify that a new process
+ group will be created. This flag is necessary for using :func:`os.kill`
+ on the subprocess.
+
+ This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
+
+
.. _subprocess-replacements:
Replacing Older Functions with the subprocess Module
diff --git a/Doc/library/sunau.rst b/Doc/library/sunau.rst
index 3f231b4..4bdb99b 100644
--- a/Doc/library/sunau.rst
+++ b/Doc/library/sunau.rst
@@ -1,4 +1,3 @@
-
:mod:`sunau` --- Read and write Sun AU files
============================================
@@ -6,6 +5,9 @@
:synopsis: Provide an interface to the Sun AU sound format.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
+**Source code:** :source:`Lib/sunau.py`
+
+--------------
The :mod:`sunau` module provides a convenient interface to the Sun AU sound
format. Note that this module is interface-compatible with the modules
diff --git a/Doc/library/symbol.rst b/Doc/library/symbol.rst
index 1735276..75a4792 100644
--- a/Doc/library/symbol.rst
+++ b/Doc/library/symbol.rst
@@ -1,4 +1,3 @@
-
:mod:`symbol` --- Constants used with Python parse trees
========================================================
@@ -6,6 +5,9 @@
:synopsis: Constants representing internal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/symbol.py`
+
+--------------
This module provides constants which represent the numeric values of internal
nodes of the parse tree. Unlike most Python constants, these use lower-case
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index 1598d96..80f4cd7 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -32,20 +32,6 @@
.. versionadded:: 2.0
-.. data:: subversion
-
- A triple (repo, branch, version) representing the Subversion information of the
- Python interpreter. *repo* is the name of the repository, ``'CPython'``.
- *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
- ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
- was built from a Subversion checkout; it contains the revision number (range)
- and possibly a trailing 'M' if there were local modifications. If the tree was
- exported (or svnversion was not available), it is the revision of
- ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.
-
- .. versionadded:: 2.5
-
-
.. data:: builtin_module_names
A tuple of strings giving the names of all modules that are compiled into this
@@ -109,6 +95,17 @@
customized by assigning another one-argument function to ``sys.displayhook``.
+.. data:: dont_write_bytecode
+
+ If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
+ import of source modules. This value is initially set to ``True`` or
+ ``False`` depending on the :option:`-B` command line option and the
+ :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it
+ yourself to control bytecode file generation.
+
+ .. versionadded:: 2.6
+
+
.. function:: excepthook(type, value, traceback)
This function prints out a given traceback and exception to ``sys.stderr``.
@@ -210,10 +207,10 @@
Python files are installed; by default, this is also ``'/usr/local'``. This can
be set at build time with the ``--exec-prefix`` argument to the
:program:`configure` script. Specifically, all configuration files (e.g. the
- :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
- '/lib/pythonversion/config'``, and shared library modules are installed in
- ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
- ``version[:3]``.
+ :file:`pyconfig.h` header file) are installed in the directory
+ :file:`{exec_prefix}/lib/python{X.Y}/config', and shared library modules are
+ installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y*
+ is the version number of Python, for example ``2.7``.
.. data:: executable
@@ -562,10 +559,10 @@
``version_info`` value may be used for a more human-friendly encoding of the
same information.
- The ``hexversion`` is a 32-bit number with the following layout
+ The ``hexversion`` is a 32-bit number with the following layout:
+-------------------------+------------------------------------------------+
- | bits (big endian order) | meaning |
+ | Bits (big endian order) | Meaning |
+=========================+================================================+
| :const:`1-8` | ``PY_MAJOR_VERSION`` (the ``2`` in |
| | ``2.1.0a3``) |
@@ -577,14 +574,14 @@
| | ``2.1.0a3``) |
+-------------------------+------------------------------------------------+
| :const:`25-28` | ``PY_RELEASE_LEVEL`` (``0xA`` for alpha, |
- | | ``0xB`` for beta, ``0xC`` for gamma and |
- | | ``0xF`` for final) |
+ | | ``0xB`` for beta, ``0xC`` for release |
+ | | candidate and ``0xF`` for final) |
+-------------------------+------------------------------------------------+
| :const:`29-32` | ``PY_RELEASE_SERIAL`` (the ``3`` in |
- | | ``2.1.0a3``) |
+ | | ``2.1.0a3``, zero for final releases) |
+-------------------------+------------------------------------------------+
- thus ``2.1.0a3`` is hexversion ``0x020100a3``
+ Thus ``2.1.0a3`` is hexversion ``0x020100a3``.
.. versionadded:: 1.5.2
@@ -595,7 +592,7 @@
internal representation of integers. The attributes are read only.
+-------------------------+----------------------------------------------+
- | attribute | explanation |
+ | Attribute | Explanation |
+=========================+==============================================+
| :const:`bits_per_digit` | number of bits held in each digit. Python |
| | integers are stored internally in base |
@@ -723,23 +720,45 @@
This string contains a platform identifier that can be used to append
platform-specific components to :data:`sys.path`, for instance.
- For Unix systems, this is the lowercased OS name as returned by ``uname -s``
- with the first part of the version as returned by ``uname -r`` appended,
- e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
+ For most Unix systems, this is the lowercased OS name as returned by ``uname
+ -s`` with the first part of the version as returned by ``uname -r`` appended,
+ e.g. ``'sunos5'``, *at the time when Python was built*. Unless you want to
+ test for a specific system version, it is therefore recommended to use the
+ following idiom::
+
+ if sys.platform.startswith('freebsd'):
+ # FreeBSD-specific code here...
+ elif sys.platform.startswith('linux'):
+ # Linux-specific code here...
+
+ .. versionchanged:: 2.7.3
+ Since lots of code check for ``sys.platform == 'linux2'``, and there is
+ no essential change between Linux 2.x and 3.x, ``sys.platform`` is always
+ set to ``'linux2'``, even on Linux 3.x. In Python 3.3 and later, the
+ value will always be set to ``'linux'``, so it is recommended to always
+ use the ``startswith`` idiom presented above.
+
For other systems, the values are:
- ================ ===========================
- System :data:`platform` value
- ================ ===========================
- Windows ``'win32'``
- Windows/Cygwin ``'cygwin'``
- Mac OS X ``'darwin'``
- OS/2 ``'os2'``
- OS/2 EMX ``'os2emx'``
- RiscOS ``'riscos'``
- AtheOS ``'atheos'``
- ================ ===========================
+ ===================== ===========================
+ System :data:`platform` value
+ ===================== ===========================
+ Linux (2.x *and* 3.x) ``'linux2'``
+ Windows ``'win32'``
+ Windows/Cygwin ``'cygwin'``
+ Mac OS X ``'darwin'``
+ OS/2 ``'os2'``
+ OS/2 EMX ``'os2emx'``
+ RiscOS ``'riscos'``
+ AtheOS ``'atheos'``
+ ===================== ===========================
+ .. seealso::
+ :attr:`os.name` has a coarser granularity. :func:`os.uname` gives
+ system-dependent version information.
+
+ The :mod:`platform` module provides detailed checks for the
+ system's identity.
.. data:: prefix
@@ -747,10 +766,10 @@
independent Python files are installed; by default, this is the string
``'/usr/local'``. This can be set at build time with the ``--prefix``
argument to the :program:`configure` script. The main collection of Python
- library modules is installed in the directory ``prefix + '/lib/pythonversion'``
+ library modules is installed in the directory :file:`{prefix}/lib/python{X.Y}``
while the platform independent header files (all except :file:`pyconfig.h`) are
- stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
- ``version[:3]``.
+ stored in :file:`{prefix}/include/python{X.Y}``, where *X.Y* is the version
+ number of Python, for example ``2.7``.
.. data:: ps1
@@ -778,17 +797,6 @@
.. versionadded:: 2.6
-.. data:: dont_write_bytecode
-
- If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
- import of source modules. This value is initially set to ``True`` or ``False``
- depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
- environment variable, but you can set it yourself to control bytecode file
- generation.
-
- .. versionadded:: 2.6
-
-
.. function:: setcheckinterval(interval)
Set the interpreter's "check interval". This integer value determines how often
@@ -980,6 +988,26 @@
replacing it, and restore the saved object.
+.. data:: subversion
+
+ A triple (repo, branch, version) representing the Subversion information of the
+ Python interpreter. *repo* is the name of the repository, ``'CPython'``.
+ *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
+ ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
+ was built from a Subversion checkout; it contains the revision number (range)
+ and possibly a trailing 'M' if there were local modifications. If the tree was
+ exported (or svnversion was not available), it is the revision of
+ ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.
+
+ .. versionadded:: 2.5
+
+ .. note::
+ Python is now `developed <http://docs.python.org/devguide/>`_ using
+ Mercurial. In recent Python 2.7 bugfix releases, :data:`subversion`
+ therefore contains placeholder information. It is removed in Python
+ 3.3.
+
+
.. data:: tracebacklimit
When this variable is set to an integer value, it determines the maximum number
diff --git a/Doc/library/sysconfig.rst b/Doc/library/sysconfig.rst
index 38aae0a..5ba6fa2 100644
--- a/Doc/library/sysconfig.rst
+++ b/Doc/library/sysconfig.rst
@@ -5,10 +5,15 @@
:synopsis: Python's configuration information
.. moduleauthor:: Tarek Ziade <tarek@ziade.org>
.. sectionauthor:: Tarek Ziade <tarek@ziade.org>
-.. versionadded:: 2.7
.. index::
single: configuration information
+.. versionadded:: 2.7
+
+**Source code:** :source:`Lib/sysconfig.py`
+
+--------------
+
The :mod:`sysconfig` module provides access to Python's configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.
diff --git a/Doc/library/tabnanny.rst b/Doc/library/tabnanny.rst
index b86971d..f447f12 100644
--- a/Doc/library/tabnanny.rst
+++ b/Doc/library/tabnanny.rst
@@ -9,6 +9,10 @@
.. rudimentary documentation based on module comments
+**Source code:** :source:`Lib/tabnanny.py`
+
+--------------
+
For the time being this module is intended to be called as a script. However it
is possible to import it into an IDE and use the function :func:`check`
described below.
diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst
index a8e1d56..5502adc 100644
--- a/Doc/library/tarfile.rst
+++ b/Doc/library/tarfile.rst
@@ -1,5 +1,3 @@
-.. _tarfile-mod:
-
:mod:`tarfile` --- Read and write tar archive files
===================================================
@@ -12,6 +10,9 @@
.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
+**Source code:** :source:`Lib/tarfile.py`
+
+--------------
The :mod:`tarfile` module makes it possible to read and write tar
archives, including those using gzip or bz2 compression.
diff --git a/Doc/library/telnetlib.rst b/Doc/library/telnetlib.rst
index 925eccc..f6340a9 100644
--- a/Doc/library/telnetlib.rst
+++ b/Doc/library/telnetlib.rst
@@ -1,4 +1,3 @@
-
:mod:`telnetlib` --- Telnet client
==================================
@@ -9,6 +8,10 @@
.. index:: single: protocol; Telnet
+**Source code:** :source:`Lib/telnetlib.py`
+
+--------------
+
The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
Telnet protocol. See :rfc:`854` for details about the protocol. In addition, it
provides symbolic constants for the protocol characters (see below), and for the
diff --git a/Doc/library/tempfile.rst b/Doc/library/tempfile.rst
index c155d66..936f06a 100644
--- a/Doc/library/tempfile.rst
+++ b/Doc/library/tempfile.rst
@@ -1,4 +1,3 @@
-
:mod:`tempfile` --- Generate temporary files and directories
============================================================
@@ -13,6 +12,10 @@
pair: temporary; file name
pair: temporary; file
+**Source code:** :source:`Lib/tempfile.py`
+
+--------------
+
This module generates temporary files and directories. It works on all
supported platforms.
@@ -61,7 +64,7 @@
This function operates exactly as :func:`TemporaryFile` does, except that
the file is guaranteed to have a visible name in the file system (on
Unix, the directory entry is not unlinked). That name can be retrieved
- from the :attr:`name` member of the file object. Whether the name can be
+ from the :attr:`name` attribute of the file object. Whether the name can be
used to open the file a second time, while the named temporary file is
still open, varies across platforms (it can be so used on Unix; it cannot
on Windows NT or later). If *delete* is true (the default), the file is
diff --git a/Doc/library/textwrap.rst b/Doc/library/textwrap.rst
index 8fbfe9c..84e6ee1 100644
--- a/Doc/library/textwrap.rst
+++ b/Doc/library/textwrap.rst
@@ -1,4 +1,3 @@
-
:mod:`textwrap` --- Text wrapping and filling
=============================================
@@ -7,20 +6,18 @@
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Greg Ward <gward@python.net>
-
.. versionadded:: 2.3
+**Source code:** :source:`Lib/textwrap.py`
+
+--------------
+
The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and
:func:`fill`, as well as :class:`TextWrapper`, the class that does all the work,
and a utility function :func:`dedent`. If you're just wrapping or filling one
or two text strings, the convenience functions should be good enough;
otherwise, you should use an instance of :class:`TextWrapper` for efficiency.
-.. seealso::
-
- Latest version of the `textwrap module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/textwrap.py?view=markup>`_
-
.. function:: wrap(text[, width[, ...]])
Wraps the single paragraph in *text* (a string) so every line is at most *width*
diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst
index 0b46349..9544466 100644
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -4,6 +4,9 @@
.. module:: threading
:synopsis: Higher-level threading interface.
+**Source code:** :source:`Lib/threading.py`
+
+--------------
This module constructs higher-level threading interfaces on top of the lower
level :mod:`thread` module.
@@ -36,11 +39,6 @@
:mod:`multiprocessing`. However, threading is still an appropriate model
if you want to run multiple I/O-bound tasks simultaneously.
-.. seealso::
-
- Latest version of the `threading module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/threading.py?view=markup>`_
-
This module defines the following functions and objects:
diff --git a/Doc/library/time.rst b/Doc/library/time.rst
index d6efcee..18a8bc6 100644
--- a/Doc/library/time.rst
+++ b/Doc/library/time.rst
@@ -560,6 +560,6 @@
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
year (%y rather than %Y), but practice moved to 4-digit years long before the
- year 2000. The 4-digit year has been mandated by :rfc:`2822`, which obsoletes
- :rfc:`822`.
+ year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has
+ been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`.
diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst
index 29a941c..7fbe19e 100644
--- a/Doc/library/timeit.rst
+++ b/Doc/library/timeit.rst
@@ -1,4 +1,3 @@
-
:mod:`timeit` --- Measure execution time of small code snippets
===============================================================
@@ -12,6 +11,10 @@
single: Benchmarking
single: Performance
+**Source code:** :source:`Lib/timeit.py`
+
+--------------
+
This module provides a simple way to time small bits of Python code. It has both
command line as well as callable interfaces. It avoids a number of common traps
for measuring execution times. See also Tim Peters' introduction to the
@@ -195,13 +198,13 @@
:keyword:`try`/:keyword:`except` to test for missing and present object
attributes. ::
- % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
+ $ python -m timeit 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
100000 loops, best of 3: 15.7 usec per loop
- % timeit.py 'if hasattr(str, "__nonzero__"): pass'
+ $ python -m timeit 'if hasattr(str, "__nonzero__"): pass'
100000 loops, best of 3: 4.26 usec per loop
- % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
+ $ python -m timeit 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
1000000 loops, best of 3: 1.43 usec per loop
- % timeit.py 'if hasattr(int, "__nonzero__"): pass'
+ $ python -m timeit 'if hasattr(int, "__nonzero__"): pass'
100000 loops, best of 3: 2.23 usec per loop
::
@@ -242,12 +245,12 @@
``setup`` parameter which contains an import statement::
def test():
- "Stupid test function"
+ """Stupid test function"""
L = []
for i in range(100):
L.append(i)
- if __name__=='__main__':
+ if __name__ == '__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
diff --git a/Doc/library/token.rst b/Doc/library/token.rst
index 00972b0..4b98eac 100644
--- a/Doc/library/token.rst
+++ b/Doc/library/token.rst
@@ -1,4 +1,3 @@
-
:mod:`token` --- Constants used with Python parse trees
=======================================================
@@ -6,6 +5,9 @@
:synopsis: Constants representing terminal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/token.py`
+
+--------------
This module provides constants which represent the numeric values of leaf nodes
of the parse tree (terminal tokens). Refer to the file :file:`Grammar/Grammar`
diff --git a/Doc/library/tokenize.rst b/Doc/library/tokenize.rst
index 2a7dea1..30677ea 100644
--- a/Doc/library/tokenize.rst
+++ b/Doc/library/tokenize.rst
@@ -1,4 +1,3 @@
-
:mod:`tokenize` --- Tokenizer for Python source
===============================================
@@ -7,17 +6,15 @@
.. moduleauthor:: Ka Ping Yee
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/tokenize.py`
+
+--------------
The :mod:`tokenize` module provides a lexical scanner for Python source code,
implemented in Python. The scanner in this module returns comments as tokens as
well, making it useful for implementing "pretty-printers," including colorizers
for on-screen displays.
-.. seealso::
-
- Latest version of the `tokenize module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/tokenize.py?view=markup>`_
-
The primary entry point is a :term:`generator`:
.. function:: generate_tokens(readline)
diff --git a/Doc/library/trace.rst b/Doc/library/trace.rst
index 2e9d2b4..a2afda1 100644
--- a/Doc/library/trace.rst
+++ b/Doc/library/trace.rst
@@ -1,21 +1,18 @@
-
:mod:`trace` --- Trace or track Python statement execution
==========================================================
.. module:: trace
:synopsis: Trace or track Python statement execution.
+**Source code:** :source:`Lib/trace.py`
+
+--------------
The :mod:`trace` module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run. It can be used in another program
or from the command line.
-.. seealso::
-
- Latest version of the `trace module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/trace.py?view=markup>`_
-
.. _trace-cli:
Command-Line Usage
diff --git a/Doc/library/turtle.rst b/Doc/library/turtle.rst
index 129ec0e..98c07ca 100644
--- a/Doc/library/turtle.rst
+++ b/Doc/library/turtle.rst
@@ -18,10 +18,10 @@
part of the original Logo programming language developed by Wally Feurzig and
Seymour Papert in 1966.
-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it the
+Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it the
command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
direction it is facing, drawing a line as it moves. Give it the command
-``turtle.left(25)``, and it rotates in-place 25 degrees clockwise.
+``turtle.right(25)``, and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and pictures
can easily be drawn.
diff --git a/Doc/library/types.rst b/Doc/library/types.rst
index 637704b..77cf014 100644
--- a/Doc/library/types.rst
+++ b/Doc/library/types.rst
@@ -4,6 +4,9 @@
.. module:: types
:synopsis: Names for built-in types.
+**Source code:** :source:`Lib/types.py`
+
+--------------
This module defines names for some object types that are used by the standard
Python interpreter, but not for the types defined by various extension modules.
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index 42ae8e2..16a3a36 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -307,7 +307,7 @@
Test discovery loads tests by importing them. Once test discovery has
found all the test files from the start directory you specify it turns the
- paths into package names to import. For example `foo/bar/baz.py` will be
+ paths into package names to import. For example :file:`foo/bar/baz.py` will be
imported as ``foo.bar.baz``.
If you have a package installed globally and attempt test discovery on
@@ -905,11 +905,11 @@
+---------------------------------------------------------+--------------------------------------+------------+
| Method | Checks that | New in |
+=========================================================+======================================+============+
- | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
+ | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | |
| <TestCase.assertRaises>` | | |
+---------------------------------------------------------+--------------------------------------+------------+
- | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 2.7 |
- | <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
+ | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 2.7 |
+ | <TestCase.assertRaisesRegexp>` | and the message matches *re* | |
+---------------------------------------------------------+--------------------------------------+------------+
.. method:: assertRaises(exception, callable, *args, **kwds)
@@ -995,7 +995,7 @@
| <TestCase.assertItemsEqual>` | works with unhashable objs | |
+---------------------------------------+--------------------------------+--------------+
| :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 2.7 |
- | <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
+ | <TestCase.assertDictContainsSubset>` | in *a* exist in *b* | |
+---------------------------------------+--------------------------------+--------------+
diff --git a/Doc/library/urllib.rst b/Doc/library/urllib.rst
index 7f97673..82f1bda 100644
--- a/Doc/library/urllib.rst
+++ b/Doc/library/urllib.rst
@@ -23,7 +23,7 @@
instead of filenames. Some restrictions apply --- it can only open URLs for
reading, and no seek operations are available.
-.. warning:: When opening HTTPS URLs, it is not attempted to validate the
+.. warning:: When opening HTTPS URLs, it does not attempt to validate the
server certificate. Use at your own risk!
@@ -210,7 +210,7 @@
Replace special characters in *string* using the ``%xx`` escape. Letters,
digits, and the characters ``'_.-'`` are never quoted. By default, this
- function is intended for quoting the path section of the URL.The optional
+ function is intended for quoting the path section of the URL. The optional
*safe* parameter specifies additional characters that should not be quoted
--- its default value is ``'/'``.
diff --git a/Doc/library/urllib2.rst b/Doc/library/urllib2.rst
index cef96a4..b66ebd7 100644
--- a/Doc/library/urllib2.rst
+++ b/Doc/library/urllib2.rst
@@ -36,7 +36,7 @@
:mimetype:`application/x-www-form-urlencoded` format. The
:func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
returns a string in this format. urllib2 module sends HTTP/1.1 requests with
- `Connection:close` header included.
+ ``Connection:close`` header included.
The optional *timeout* parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
@@ -90,7 +90,7 @@
:class:`HTTPSHandler` will also be added.
Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
- :attr:`handler_order` member variable to modify its position in the handlers
+ :attr:`handler_order` attribute to modify its position in the handlers
list.
The following exceptions are raised as appropriate:
@@ -297,6 +297,11 @@
A catch-all class to handle unknown URLs.
+.. class:: HTTPErrorProcessor()
+
+ Process HTTP error responses.
+
+
.. _request-objects:
Request Objects
@@ -495,7 +500,7 @@
Remove any parents.
-The following members and methods should only be used by classes derived from
+The following attributes and methods should only be used by classes derived from
:class:`BaseHandler`.
.. note::
@@ -881,7 +886,7 @@
.. versionadded:: 2.4
-.. method:: HTTPErrorProcessor.unknown_open()
+.. method:: HTTPErrorProcessor.http_response()
Process HTTP error responses.
@@ -893,6 +898,12 @@
:class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
other handler handles the error.
+.. method:: HTTPErrorProcessor.https_response()
+
+ Process HTTPS error responses.
+
+ The behavior is same as :meth:`http_response`.
+
.. _urllib2-examples:
diff --git a/Doc/library/urlparse.rst b/Doc/library/urlparse.rst
index 88dafa9..f118845 100644
--- a/Doc/library/urlparse.rst
+++ b/Doc/library/urlparse.rst
@@ -17,6 +17,9 @@
The :term:`2to3` tool will automatically adapt imports when converting
your sources to 3.0.
+**Source code:** :source:`Lib/urlparse.py`
+
+--------------
This module defines a standard interface to break Uniform Resource Locator (URL)
strings up in components (addressing scheme, network location, path etc.), to
@@ -33,11 +36,6 @@
.. versionadded:: 2.5
Support for the ``sftp`` and ``sips`` schemes.
-.. seealso::
-
- Latest version of the `urlparse module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/urlparse.py?view=markup>`_
-
The :mod:`urlparse` module defines the following functions:
diff --git a/Doc/library/userdict.rst b/Doc/library/userdict.rst
index ab9ab04..1c75674 100644
--- a/Doc/library/userdict.rst
+++ b/Doc/library/userdict.rst
@@ -1,4 +1,3 @@
-
:mod:`UserDict` --- Class wrapper for dictionary objects
========================================================
@@ -6,6 +5,10 @@
:synopsis: Class wrapper for dictionary objects.
+**Source code:** :source:`Lib/UserDict.py`
+
+--------------
+
The module defines a mixin, :class:`DictMixin`, defining all dictionary methods
for classes that already have a minimum mapping interface. This greatly
simplifies writing classes that need to be substitutable for dictionaries (such
@@ -19,11 +22,6 @@
sub-classes that obtained new behaviors by overriding existing methods or adding
new ones.
-.. seealso::
-
- Latest version of the `UserDict Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/UserDict.py?view=markup>`_
-
The :mod:`UserDict` module defines the :class:`UserDict` class and
:class:`DictMixin`:
diff --git a/Doc/library/uu.rst b/Doc/library/uu.rst
index fa1477b..1608d41 100644
--- a/Doc/library/uu.rst
+++ b/Doc/library/uu.rst
@@ -1,4 +1,3 @@
-
:mod:`uu` --- Encode and decode uuencode files
==============================================
@@ -6,6 +5,9 @@
:synopsis: Encode and decode files in uuencode format.
.. moduleauthor:: Lance Ellinghouse
+**Source code:** :source:`Lib/uu.py`
+
+--------------
This module encodes and decodes files in uuencode format, allowing arbitrary
binary data to be transferred over ASCII-only connections. Wherever a file
@@ -22,11 +24,6 @@
This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.
-.. seealso::
-
- Latest version of the `uu module Python source code
- <http://svn.python.org/view/python/branches/release27-maint/Lib/uu.py?view=markup>`_
-
The :mod:`uu` module defines the following functions:
@@ -62,4 +59,3 @@
Module :mod:`binascii`
Support module containing ASCII-to-binary and binary-to-ASCII conversions.
-
diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst
index 544d9f7..dbcf148 100644
--- a/Doc/library/warnings.rst
+++ b/Doc/library/warnings.rst
@@ -9,6 +9,10 @@
.. versionadded:: 2.1
+**Source code:** :source:`Lib/warnings.py`
+
+--------------
+
Warning messages are typically issued in situations where it is useful to alert
the user of some condition in a program, where that condition (normally) doesn't
warrant raising an exception and terminating the program. For example, one
@@ -39,6 +43,10 @@
message by calling :func:`formatwarning`, which is also available for use by
custom implementations.
+.. seealso::
+ :func:`logging.captureWarnings` allows you to handle all warnings with
+ the standard logging infrastructure.
+
.. _warning-categories:
diff --git a/Doc/library/wave.rst b/Doc/library/wave.rst
index c1db523..93ea5e0 100644
--- a/Doc/library/wave.rst
+++ b/Doc/library/wave.rst
@@ -6,6 +6,10 @@
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
.. Documentations stolen from comments in file.
+**Source code:** :source:`Lib/wave.py`
+
+--------------
+
The :mod:`wave` module provides a convenient interface to the WAV sound format.
It does not support compression/decompression, but it does support mono/stereo.
diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst
index 9c65587..7929c51 100644
--- a/Doc/library/weakref.rst
+++ b/Doc/library/weakref.rst
@@ -11,6 +11,10 @@
.. versionadded:: 2.1
+**Source code:** :source:`Lib/weakref.py`
+
+--------------
+
The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
references` to objects.
diff --git a/Doc/library/webbrowser.rst b/Doc/library/webbrowser.rst
index 74e12a2..1a27d07 100644
--- a/Doc/library/webbrowser.rst
+++ b/Doc/library/webbrowser.rst
@@ -1,4 +1,3 @@
-
:mod:`webbrowser` --- Convenient Web-browser controller
=======================================================
@@ -7,6 +6,9 @@
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
+**Source code:** :source:`Lib/webbrowser.py`
+
+--------------
The :mod:`webbrowser` module provides a high-level interface to allow displaying
Web-based documents to users. Under most circumstances, simply calling the
diff --git a/Doc/library/xdrlib.rst b/Doc/library/xdrlib.rst
index 3297975..e56650c 100644
--- a/Doc/library/xdrlib.rst
+++ b/Doc/library/xdrlib.rst
@@ -1,4 +1,3 @@
-
:mod:`xdrlib` --- Encode and decode XDR data
============================================
@@ -10,6 +9,10 @@
single: XDR
single: External Data Representation
+**Source code:** :source:`Lib/xdrlib.py`
+
+--------------
+
The :mod:`xdrlib` module supports the External Data Representation Standard as
described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987. It
supports most of the data types described in the RFC.
@@ -257,7 +260,7 @@
.. exception:: Error
- The base exception class. :exc:`Error` has a single public data member
+ The base exception class. :exc:`Error` has a single public attribute
:attr:`msg` containing the description of the error.
diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst
index 064ddd4..69e9e56 100644
--- a/Doc/library/xml.dom.minidom.rst
+++ b/Doc/library/xml.dom.minidom.rst
@@ -1,4 +1,3 @@
-
:mod:`xml.dom.minidom` --- Lightweight DOM implementation
=========================================================
@@ -11,6 +10,10 @@
.. versionadded:: 2.0
+**Source code:** :source:`Lib/xml/dom/minidom.py`
+
+--------------
+
:mod:`xml.dom.minidom` is a light-weight implementation of the Document Object
Model interface. It is intended to be simpler than the full DOM and also
significantly smaller.
diff --git a/Doc/library/xml.dom.pulldom.rst b/Doc/library/xml.dom.pulldom.rst
index 80a91b8..bad0daa 100644
--- a/Doc/library/xml.dom.pulldom.rst
+++ b/Doc/library/xml.dom.pulldom.rst
@@ -1,4 +1,3 @@
-
:mod:`xml.dom.pulldom` --- Support for building partial DOM trees
=================================================================
@@ -9,6 +8,10 @@
.. versionadded:: 2.0
+**Source code:** :source:`Lib/xml/dom/pulldom.py`
+
+--------------
+
:mod:`xml.dom.pulldom` allows building only selected portions of a Document
Object Model representation of a document from SAX events.
diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst
index def4669..5fbbf20 100644
--- a/Doc/library/xml.etree.elementtree.rst
+++ b/Doc/library/xml.etree.elementtree.rst
@@ -1,4 +1,3 @@
-
:mod:`xml.etree.ElementTree` --- The ElementTree XML API
========================================================
@@ -9,6 +8,10 @@
.. versionadded:: 2.5
+**Source code:** :source:`Lib/xml/etree/ElementTree.py`
+
+--------------
+
The :class:`Element` type is a flexible container object, designed to store
hierarchical data structures in memory. The type can be described as a cross
between a list and a dictionary.
@@ -333,6 +336,8 @@
elements whose tag equals *tag* are returned from the iterator. If the
tree structure is modified during iteration, the result is undefined.
+ .. versionadded:: 2.7
+
.. method:: iterfind(match)
diff --git a/Doc/library/xmlrpclib.rst b/Doc/library/xmlrpclib.rst
index cc2e8b6..183be92 100644
--- a/Doc/library/xmlrpclib.rst
+++ b/Doc/library/xmlrpclib.rst
@@ -17,6 +17,10 @@
.. versionadded:: 2.2
+**Source code:** :source:`Lib/xmlrpclib.py`
+
+--------------
+
XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
transport. With it, a client can call methods with parameters on a remote
server (the server is named by a URI) and get back structured data. This module
@@ -148,7 +152,7 @@
:class:`Fault` or :class:`ProtocolError` object indicating an error.
Servers that support the XML introspection API support some common methods
-grouped under the reserved :attr:`system` member:
+grouped under the reserved :attr:`system` attribute:
.. method:: ServerProxy.system.listMethods()
@@ -341,7 +345,7 @@
-------------
A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
-objects have the following members:
+objects have the following attributes:
.. attribute:: Fault.faultCode
@@ -390,7 +394,7 @@
A :class:`ProtocolError` object describes a protocol error in the underlying
transport layer (such as a 404 'not found' error if the server named by the URI
-does not exist). It has the following members:
+does not exist). It has the following attributes:
.. attribute:: ProtocolError.url
@@ -435,8 +439,8 @@
.. versionadded:: 2.4
-In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
-encapsulate multiple calls to a remote server into a single request.
+The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
+remote server into a single request [#]_.
.. class:: MultiCall(server)
@@ -577,3 +581,10 @@
See :ref:`simplexmlrpcserver-example`.
+.. rubric:: Footnotes
+
+.. [#] This approach has been first presented in `a discussion on xmlrpc.com
+ <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
+.. the link now points to webarchive since the one at
+.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
+.. doesn't reply)
diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst
index 51240ba..30a0361 100644
--- a/Doc/library/zipfile.rst
+++ b/Doc/library/zipfile.rst
@@ -1,4 +1,3 @@
-
:mod:`zipfile` --- Work with ZIP archives
=========================================
@@ -9,6 +8,10 @@
.. versionadded:: 1.6
+**Source code:** :source:`Lib/zipfile.py`
+
+--------------
+
The ZIP file format is a common archive and compression standard. This module
provides tools to create, read, write, append, and list a ZIP file. Any
advanced use of this module will require an understanding of the format, as
diff --git a/Doc/library/zipimport.rst b/Doc/library/zipimport.rst
index 43e12b1..af18d15 100644
--- a/Doc/library/zipimport.rst
+++ b/Doc/library/zipimport.rst
@@ -12,11 +12,11 @@
This module adds the ability to import Python modules (:file:`\*.py`,
:file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not
needed to use the :mod:`zipimport` module explicitly; it is automatically used
-by the built-in :keyword:`import` mechanism for ``sys.path`` items that are paths
+by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths
to ZIP archives.
-Typically, ``sys.path`` is a list of directory names as strings. This module
-also allows an item of ``sys.path`` to be a string naming a ZIP file archive.
+Typically, :data:`sys.path` is a list of directory names as strings. This module
+also allows an item of :data:`sys.path` to be a string naming a ZIP file archive.
The ZIP archive can contain a subdirectory structure to support package imports,
and a path within the archive can be specified to only import from a
subdirectory. For example, the path :file:`/tmp/example.zip/lib/` would only
diff --git a/Doc/license.rst b/Doc/license.rst
index 4c654ae..1469785 100644
--- a/Doc/license.rst
+++ b/Doc/license.rst
@@ -536,36 +536,6 @@
PERFORMANCE OF THIS SOFTWARE.
-Profiling
----------
-
-The :mod:`profile` and :mod:`pstats` modules contain the following notice::
-
- Copyright 1994, by InfoSeek Corporation, all rights reserved.
- Written by James Roskind
-
- Permission to use, copy, modify, and distribute this Python software
- and its associated documentation for any purpose (subject to the
- restriction in the following sentence) without fee is hereby granted,
- provided that the above copyright notice appears in all copies, and
- that both that copyright notice and this permission notice appear in
- supporting documentation, and that the name of InfoSeek not be used in
- advertising or publicity pertaining to distribution of the software
- without specific, written prior permission. This permission is
- explicitly restricted to the copying and modification of the software
- to remain in Python, compiled Python, or other languages (such as C)
- wherein the modified or derived code is exclusively imported into a
- Python module.
-
- INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
- SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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.
-
-
Execution tracing
-----------------
@@ -889,7 +859,7 @@
-----
The :mod:`pyexpat` extension is built using an included copy of the expat
-sources unless the build is configured :option:`--with-system-expat`::
+sources unless the build is configured ``--with-system-expat``::
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
@@ -918,7 +888,7 @@
------
The :mod:`_ctypes` extension is built using an included copy of the libffi
-sources unless the build is configured :option:`--with-system-libffi`::
+sources unless the build is configured ``--with-system-libffi``::
Copyright (c) 1996-2008 Red Hat, Inc and others.
@@ -947,7 +917,7 @@
----
The :mod:`zlib` extension is built using an included copy of the zlib
-sources unless the zlib version found on the system is too old to be
+sources if the zlib version found on the system is too old to be
used for the build::
Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
diff --git a/Doc/reference/compound_stmts.rst b/Doc/reference/compound_stmts.rst
index 9dfa31f..7015a7f 100644
--- a/Doc/reference/compound_stmts.rst
+++ b/Doc/reference/compound_stmts.rst
@@ -562,8 +562,9 @@
.. rubric:: Footnotes
-.. [#] The exception is propagated to the invocation stack only if there is no
- :keyword:`finally` clause that negates the exception.
+.. [#] The exception is propagated to the invocation stack unless
+ there is a :keyword:`finally` clause which happens to raise another
+ exception. That new exception causes the old one to be lost.
.. [#] Currently, control "flows off the end" except in the case of an exception or the
execution of a :keyword:`return`, :keyword:`continue`, or :keyword:`break`
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 7c2c9af..0cd4c62 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -2308,7 +2308,7 @@
*
- In ``x * y``, if one operator is a sequence that implements sequence
+ In ``x * y``, if one operand is a sequence that implements sequence
repetition, and the other is an integer (:class:`int` or :class:`long`),
sequence repetition is invoked.
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index 067a3d6..e2cc80d 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -735,12 +735,15 @@
and the argument values as corresponding values), or a (new) empty dictionary if
there were no excess keyword arguments.
+.. index::
+ single: *; in function calls
+
If the syntax ``*expression`` appears in the function call, ``expression`` must
-evaluate to a sequence. Elements from this sequence are treated as if they were
-additional positional arguments; if there are positional arguments *x1*,...,
-*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
-equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
-*yM*.
+evaluate to an iterable. Elements from this iterable are treated as if they
+were additional positional arguments; if there are positional arguments
+*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this
+is equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*,
+..., *yM*.
A consequence of this is that although the ``*expression`` syntax may appear
*after* some keyword arguments, it is processed *before* the keyword arguments
@@ -761,6 +764,9 @@
It is unusual for both keyword arguments and the ``*expression`` syntax to be
used in the same call, so in practice this confusion does not arise.
+.. index::
+ single: **; in function calls
+
If the syntax ``**expression`` appears in the function call, ``expression`` must
evaluate to a mapping, the contents of which are treated as additional keyword
arguments. In the case of a keyword appearing in both ``expression`` and as an
diff --git a/Doc/tools/sphinxext/pyspecific.py b/Doc/tools/sphinxext/pyspecific.py
index 415310d..a588b4d 100644
--- a/Doc/tools/sphinxext/pyspecific.py
+++ b/Doc/tools/sphinxext/pyspecific.py
@@ -5,11 +5,12 @@
Sphinx extension with Python doc-specific markup.
- :copyright: 2008, 2009 by Georg Brandl.
+ :copyright: 2008-2011 by Georg Brandl.
:license: Python license.
"""
ISSUE_URI = 'http://bugs.python.org/issue%s'
+SOURCE_URI = 'http://hg.python.org/cpython/file/2.7/%s'
from docutils import nodes, utils
@@ -44,6 +45,14 @@
return [refnode], []
+# Support for linking to Python source files easily
+
+def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
+ path = utils.unescape(text)
+ refnode = nodes.reference(path, path, refuri=SOURCE_URI % path)
+ return [refnode], []
+
+
# Support for marking up implementation details
from sphinx.util.compat import Directive
@@ -168,6 +177,7 @@
def setup(app):
app.add_role('issue', issue_role)
+ app.add_role('source', source_role)
app.add_directive('impl-detail', ImplementationDetail)
app.add_builder(PydocTopicsBuilder)
app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
diff --git a/Doc/tools/sphinxext/susp-ignored.csv b/Doc/tools/sphinxext/susp-ignored.csv
index a97b764..e82a82b 100644
--- a/Doc/tools/sphinxext/susp-ignored.csv
+++ b/Doc/tools/sphinxext/susp-ignored.csv
@@ -5,7 +5,6 @@
c-api/sequence,,:i2,o[i1:i2] = v
c-api/sequence,,:i2,del o[i1:i2]
c-api/unicode,,:end,str[start:end]
-distutils/apiref,,:action,http://pypi.python.org/pypi?:action=list_classifiers
distutils/setupscript,,::,
extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))"
extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {"
@@ -222,6 +221,9 @@
whatsnew/2.7,862,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0"
whatsnew/2.7,,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
whatsnew/2.7,,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',"
+howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so
+howto/pyporting,75,::,"'Programming Language :: Python',"
+howto/pyporting,75,::,'Programming Language :: Python :: 3'
documenting/markup,33,.. sectionauthor:,.. sectionauthor:: Guido van Rossum <guido@python.org>
documenting/markup,42,:mod,:mod:`parrot` -- Dead parrot access
documenting/markup,42,`,:mod:`parrot` -- Dead parrot access
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index ed0e655..c3640a0 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -553,6 +553,28 @@
without regard to the syntactic position of the identifier, as long as it
occurs within the definition of a class.
+Name mangling is helpful for letting subclasses override methods without
+breaking intraclass method calls. For example::
+
+ class Mapping:
+ def __init__(self, iterable):
+ self.items_list = []
+ self.__update(iterable)
+
+ def update(self, iterable):
+ for item in iterable:
+ self.items_list.append(item)
+
+ __update = update # private copy of original update() method
+
+ class MappingSubclass(Mapping):
+
+ def update(self, keys, values):
+ # provides new signature for update()
+ # but does not break __init__()
+ for item in zip(keys, values):
+ self.items_list.append(item)
+
Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private. This can
even be useful in special circumstances, such as in the debugger.
@@ -687,7 +709,6 @@
>>> it.next()
'c'
>>> it.next()
-
Traceback (most recent call last):
File "<stdin>", line 1, in ?
it.next()
@@ -699,7 +720,7 @@
:meth:`next`, then :meth:`__iter__` can just return ``self``::
class Reverse:
- "Iterator for looping over a sequence backwards"
+ """Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
@@ -711,6 +732,8 @@
self.index = self.index - 1
return self.data[self.index]
+::
+
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
@@ -739,6 +762,8 @@
for index in range(len(data)-1, -1, -1):
yield data[index]
+::
+
>>> for char in reverse('golf'):
... print char
...
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index de93beb..43a8382 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -156,6 +156,9 @@
8 equals 2 * 4
9 equals 3 * 3
+(Yes, this is the correct code. Look closely: the ``else`` clause belongs to
+the :keyword:`for` loop, **not** the :keyword:`if` statement.)
+
.. _tut-pass:
@@ -455,10 +458,9 @@
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
-Note that the :meth:`sort` method of the list of keyword argument names is
-called before printing the contents of the ``keywords`` dictionary; if this is
-not done, the order in which the arguments are printed is undefined.
-
+Note that the list of keyword argument names is created by sorting the result
+of the keywords dictionary's ``keys()`` method before printing its contents;
+if this is not done, the order in which the arguments are printed is undefined.
.. _tut-arbitraryargs:
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index 226eadd..97e0ee8 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -170,8 +170,8 @@
``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 primes up
-to 25::
+otherwise, it is always a :class:`list`. For example, to compute a sequence of
+numbers not divisible by 2 and 3::
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
diff --git a/Doc/tutorial/interactive.rst b/Doc/tutorial/interactive.rst
index 5faaf96..36acb06 100644
--- a/Doc/tutorial/interactive.rst
+++ b/Doc/tutorial/interactive.rst
@@ -156,17 +156,18 @@
quotes, etc., would also be useful.
One alternative enhanced interactive interpreter that has been around for quite
-some time is `IPython`_, which features tab completion, object exploration and
+some time is IPython_, which features tab completion, object exploration and
advanced history management. It can also be thoroughly customized and embedded
into other applications. Another similar enhanced interactive environment is
-`bpython`_.
+bpython_.
.. rubric:: Footnotes
.. [#] Python will execute the contents of a file identified by the
:envvar:`PYTHONSTARTUP` environment variable when you start an interactive
- interpreter.
+ interpreter. To customize Python even for non-interactive mode, see
+ :ref:`tut-customize`.
.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst
index df93af2..87e5696 100644
--- a/Doc/tutorial/interpreter.rst
+++ b/Doc/tutorial/interpreter.rst
@@ -166,6 +166,8 @@
suppressed.
+.. _tut-source-encoding:
+
Source Code Encoding
--------------------
@@ -240,7 +242,29 @@
execfile(filename)
+.. _tut-customize:
+
+The Customization Modules
+-------------------------
+
+Python provides two hooks to let you customize it: :mod:`sitecustomize` and
+:mod:`usercustomize`. To see how it works, you need first to find the location
+of your user site-packages directory. Start Python and run this code:
+
+ >>> import site
+ >>> site.getusersitepackages()
+ '/home/user/.local/lib/python3.2/site-packages'
+
+Now you can create a file named :file:`usercustomize.py` in that directory and
+put anything you want in it. It will affect every invocation of Python, unless
+it is started with the :option:`-s` option to disable the automatic import.
+
+:mod:`sitecustomize` works in the same way, but is typically created by an
+administrator of the computer in the global site-packages directory, and is
+imported before :mod:`usercustomize`. See the documentation of the :mod:`site`
+module for more details.
+
+
.. rubric:: Footnotes
.. [#] A problem with the GNU Readline package may prevent this.
-
diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst
index 6f51357..12f649e 100644
--- a/Doc/tutorial/modules.rst
+++ b/Doc/tutorial/modules.rst
@@ -155,13 +155,14 @@
.. index:: triple: module; search; path
-When a module named :mod:`spam` is imported, the interpreter searches for a file
-named :file:`spam.py` in the current directory, and then in the list of
-directories specified by the environment variable :envvar:`PYTHONPATH`. This
-has the same syntax as the shell variable :envvar:`PATH`, that is, a list of
-directory names. When :envvar:`PYTHONPATH` is not set, or when the file is not
-found there, the search continues in an installation-dependent default path; on
-Unix, this is usually :file:`.:/usr/local/lib/python`.
+When a module named :mod:`spam` is imported, the interpreter searches for a
+file named :file:`spam.py` in the directory containing the input script and
+then in the list of directories specified by the environment variable
+:envvar:`PYTHONPATH`. This has the same syntax as the shell variable
+:envvar:`PATH`, that is, a list of directory names. When :envvar:`PYTHONPATH`
+is not set, or when the file is not found there, the search continues in an
+installation-dependent default path; on Unix, this is usually
+:file:`.:/usr/local/lib/python`.
Actually, modules are searched in the list of directories given by the variable
``sys.path`` which is initialized from the directory containing the input script
diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst
index a10ab1c..fed83df 100644
--- a/Doc/using/cmdline.rst
+++ b/Doc/using/cmdline.rst
@@ -255,7 +255,8 @@
.. cmdoption:: -s
- Don't add user site directory to sys.path
+ Don't add the :data:`user site-packages directory <site.USER_SITE>` to
+ :data:`sys.path`.
.. versionadded:: 2.6
@@ -532,7 +533,8 @@
.. envvar:: PYTHONNOUSERSITE
- If this is set, Python won't add the user site directory to sys.path
+ If this is set, Python won't add the :data:`user site-packages directory
+ <site.USER_SITE>` to :data:`sys.path`.
.. versionadded:: 2.6
@@ -543,7 +545,10 @@
.. envvar:: PYTHONUSERBASE
- Sets the base directory for the user site directory
+ Defines the :data:`user base directory <site.USER_BASE>`, which is used to
+ compute the path of the :data:`user site-packages directory <site.USER_SITE>`
+ and :ref:`Distutils installation paths <inst-alt-install-user>` for ``python
+ setup.py install --user``.
.. versionadded:: 2.6
@@ -569,7 +574,7 @@
~~~~~~~~~~~~~~~~~~~~
Setting these variables only has an effect in a debug build of Python, that is,
-if Python was configured with the :option:`--with-pydebug` build option.
+if Python was configured with the ``--with-pydebug`` build option.
.. envvar:: PYTHONTHREADDEBUG
diff --git a/Doc/using/unix.rst b/Doc/using/unix.rst
index 61e707b..8060d41 100644
--- a/Doc/using/unix.rst
+++ b/Doc/using/unix.rst
@@ -1,4 +1,4 @@
-.. highlightlang:: none
+.. highlightlang:: sh
.. _using-on-unix:
@@ -55,8 +55,8 @@
On OpenSolaris
--------------
-To install the newest Python versions on OpenSolaris, install blastwave
-(http://www.blastwave.org/howto.html) and type "pkg_get -i python" at the
+To install the newest Python versions on OpenSolaris, install `blastwave
+<http://www.blastwave.org/howto.html>`_ and type ``pkg_get -i python`` at the
prompt.
@@ -65,17 +65,18 @@
If you want to compile CPython yourself, first thing you should do is get the
`source <http://python.org/download/source/>`_. You can download either the
-latest release's source or just grab a fresh `checkout
-<http://www.python.org/dev/faq/#how-do-i-get-a-checkout-of-the-repository-read-only-and-read-write>`_.
+latest release's source or just grab a fresh `clone
+<http://docs.python.org/devguide/setup#getting-the-source-code>`_. (If you want
+to contribute patches, you will need a clone.)
-The build process consists the usual ::
+The build process consists in the usual ::
./configure
make
make install
invocations. Configuration options and caveats for specific Unix platforms are
-extensively documented in the :file:`README` file in the root of the Python
+extensively documented in the :source:`README` file in the root of the Python
source tree.
.. warning::
diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst
index c7f7d58..2825dd4 100644
--- a/Doc/whatsnew/2.5.rst
+++ b/Doc/whatsnew/2.5.rst
@@ -1459,7 +1459,7 @@
On FreeBSD, the :func:`os.stat` function now returns times with nanosecond
resolution, and the returned object now has :attr:`st_gen` and
- :attr:`st_birthtime`. The :attr:`st_flags` member is also available, if the
+ :attr:`st_birthtime`. The :attr:`st_flags` attribute is also available, if the
platform supports it. (Contributed by Antti Louko and Diego Pettenò.)
.. (Patch 1180695, 1212117)
diff --git a/Doc/whatsnew/2.7.rst b/Doc/whatsnew/2.7.rst
index 6cd3aba..43b859d 100644
--- a/Doc/whatsnew/2.7.rst
+++ b/Doc/whatsnew/2.7.rst
@@ -783,8 +783,8 @@
(Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
-* The :keyword:`import` statement will no longer try a relative import
- if an absolute import (e.g. ``from .os import sep``) fails. This
+* The :keyword:`import` statement will no longer try an absolute import
+ if a relative import (e.g. ``from .os import sep``) fails. This
fixes a bug, but could possibly break certain :keyword:`import`
statements that were only working by accident. (Fixed by Meador Inge;
:issue:`7902`.)
@@ -1946,7 +1946,7 @@
version 1.3. Some of the new features are:
* The various parsing functions now take a *parser* keyword argument
- giving an :class:`XMLParser` instance that will
+ giving an :class:`~xml.etree.ElementTree.XMLParser` instance that will
be used. This makes it possible to override the file's internal encoding::
p = ET.XMLParser(encoding='utf-8')
@@ -1958,8 +1958,8 @@
* ElementTree's code for converting trees to a string has been
significantly reworked, making it roughly twice as fast in many
- cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
- :meth:`write` methods now have a *method* parameter that can be
+ cases. The :meth:`ElementTree.write() <xml.etree.ElementTree.ElementTree.write>`
+ and :meth:`Element.write` methods now have a *method* parameter that can be
"xml" (the default), "html", or "text". HTML mode will output empty
elements as ``<empty></empty>`` instead of ``<empty/>``, and text
mode will skip over elements and only output the text chunks. If
@@ -1972,11 +1972,12 @@
declarations are now output on the root element, not scattered throughout
the resulting XML. You can set the default namespace for a tree
by setting the :attr:`default_namespace` attribute and can
- register new prefixes with :meth:`register_namespace`. In XML mode,
+ register new prefixes with :meth:`~xml.etree.ElementTree.register_namespace`. In XML mode,
you can use the true/false *xml_declaration* parameter to suppress the
XML declaration.
-* New :class:`Element` method: :meth:`extend` appends the items from a
+* New :class:`~xml.etree.ElementTree.Element` method:
+ :meth:`~xml.etree.ElementTree.Element.extend` appends the items from a
sequence to the element's children. Elements themselves behave like
sequences, so it's easy to move children from one element to
another::
@@ -1992,13 +1993,15 @@
# Outputs <root><item>1</item>...</root>
print ET.tostring(new)
-* New :class:`Element` method: :meth:`iter` yields the children of the
+* New :class:`Element` method:
+ :meth:`~xml.etree.ElementTree.Element.iter` yields the children of the
element as a generator. It's also possible to write ``for child in
elem:`` to loop over an element's children. The existing method
:meth:`getiterator` is now deprecated, as is :meth:`getchildren`
which constructs and returns a list of children.
-* New :class:`Element` method: :meth:`itertext` yields all chunks of
+* New :class:`Element` method:
+ :meth:`~xml.etree.ElementTree.Element.itertext` yields all chunks of
text that are descendants of the element. For example::
t = ET.XML("""<list>
diff --git a/Include/fileobject.h b/Include/fileobject.h
index ba506ec..1b540f9 100644
--- a/Include/fileobject.h
+++ b/Include/fileobject.h
@@ -84,6 +84,13 @@
#define _PyVerify_fd(A) (1) /* dummy */
#endif
+/* A routine to check if a file descriptor can be select()-ed. */
+#ifdef HAVE_SELECT
+ #define _PyIsSelectable_fd(FD) (((FD) >= 0) && ((FD) < FD_SETSIZE))
+#else
+ #define _PyIsSelectable_fd(FD) (1)
+#endif /* HAVE_SELECT */
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/patchlevel.h b/Include/patchlevel.h
index 12f599c..d697460 100644
--- a/Include/patchlevel.h
+++ b/Include/patchlevel.h
@@ -22,12 +22,12 @@
/*--start constants--*/
#define PY_MAJOR_VERSION 2
#define PY_MINOR_VERSION 7
-#define PY_MICRO_VERSION 1
+#define PY_MICRO_VERSION 2
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
#define PY_RELEASE_SERIAL 0
/* Version as a string */
-#define PY_VERSION "2.7.1+"
+#define PY_VERSION "2.7.2+"
/*--end constants--*/
/* Subversion Revision number of this file (not of the repository). Empty
diff --git a/Include/pyctype.h b/Include/pyctype.h
index c5cc614..673cf2e 100644
--- a/Include/pyctype.h
+++ b/Include/pyctype.h
@@ -9,7 +9,7 @@
#define PY_CTF_SPACE 0x08
#define PY_CTF_XDIGIT 0x10
-extern const unsigned int _Py_ctype_table[256];
+PyAPI_DATA(const unsigned int) _Py_ctype_table[256];
/* Unlike their C counterparts, the following macros are not meant to
* handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument
@@ -22,8 +22,8 @@
#define Py_ISALNUM(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALNUM)
#define Py_ISSPACE(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_SPACE)
-extern const unsigned char _Py_ctype_tolower[256];
-extern const unsigned char _Py_ctype_toupper[256];
+PyAPI_DATA(const unsigned char) _Py_ctype_tolower[256];
+PyAPI_DATA(const unsigned char) _Py_ctype_toupper[256];
#define Py_TOLOWER(c) (_Py_ctype_tolower[Py_CHARMASK(c)])
#define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)])
diff --git a/Include/pystate.h b/Include/pystate.h
index b9fe61e..8d74940 100644
--- a/Include/pystate.h
+++ b/Include/pystate.h
@@ -168,7 +168,7 @@
/* Helper/diagnostic function - get the current thread state for
this thread. May return NULL if no GILState API has been used
- on the current thread. Note the main thread always has such a
+ on the current thread. Note that the main thread always has such a
thread-state, even if no auto-thread-state call has been made
on the main thread.
*/
diff --git a/Lib/ConfigParser.py b/Lib/ConfigParser.py
index 6cf3c2a..963a418 100644
--- a/Lib/ConfigParser.py
+++ b/Lib/ConfigParser.py
@@ -570,7 +570,7 @@
def keys(self):
result = []
seen = set()
- for mapping in self_maps:
+ for mapping in self._maps:
for key in mapping:
if key not in seen:
result.append(key)
diff --git a/Lib/HTMLParser.py b/Lib/HTMLParser.py
index e018901..884d2a5 100644
--- a/Lib/HTMLParser.py
+++ b/Lib/HTMLParser.py
@@ -99,7 +99,7 @@
markupbase.ParserBase.reset(self)
def feed(self, data):
- """Feed data to the parser.
+ r"""Feed data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n').
diff --git a/Lib/StringIO.py b/Lib/StringIO.py
index 340fae1..f74a066 100644
--- a/Lib/StringIO.py
+++ b/Lib/StringIO.py
@@ -266,6 +266,7 @@
8th bit) will cause a UnicodeError to be raised when getvalue()
is called.
"""
+ _complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index dc68d04..76a2d5f 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -560,7 +560,11 @@
if not data:
break
res += data
- return bytes(res)
+ if res:
+ return bytes(res)
+ else:
+ # b'' or None
+ return data
def readinto(self, b):
"""Read up to len(b) bytes into b.
diff --git a/Lib/anydbm.py b/Lib/anydbm.py
index 8b01ef3..ba7e905 100644
--- a/Lib/anydbm.py
+++ b/Lib/anydbm.py
@@ -29,17 +29,8 @@
list = d.keys() # return a list of all existing keys (slow!)
Future versions may change the order in which implementations are
-tested for existence, add interfaces to other dbm-like
+tested for existence, and add interfaces to other dbm-like
implementations.
-
-The open function has an optional second argument. This can be 'r',
-for read-only access, 'w', for read-write access of an existing
-database, 'c' for read-write access to a new or existing database, and
-'n' for read-write access to a new database. The default is 'r'.
-
-Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
-only if it doesn't exist; and 'n' always creates a new database.
-
"""
class error(Exception):
@@ -63,7 +54,18 @@
error = tuple(_errors)
-def open(file, flag = 'r', mode = 0666):
+def open(file, flag='r', mode=0666):
+ """Open or create database at path given by *file*.
+
+ Optional argument *flag* can be 'r' (default) for read-only access, 'w'
+ for read-write access of an existing database, 'c' for read-write access
+ to a new or existing database, and 'n' for read-write access to a new
+ database.
+
+ Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
+ only if it doesn't exist; and 'n' always creates a new database.
+ """
+
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
diff --git a/Lib/asyncore.py b/Lib/asyncore.py
index 1a623db..35db387 100644
--- a/Lib/asyncore.py
+++ b/Lib/asyncore.py
@@ -132,7 +132,8 @@
is_w = obj.writable()
if is_r:
r.append(fd)
- if is_w:
+ # accepting sockets should not be writable
+ if is_w and not obj.accepting:
w.append(fd)
if is_r or is_w:
e.append(fd)
@@ -179,7 +180,8 @@
flags = 0
if obj.readable():
flags |= select.POLLIN | select.POLLPRI
- if obj.writable():
+ # accepting sockets should not be writable
+ if obj.writable() and not obj.accepting:
flags |= select.POLLOUT
if flags:
# Only check for exceptions if object was either readable
diff --git a/Lib/collections.py b/Lib/collections.py
index d87c55d..958e523 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -312,6 +312,7 @@
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self)) \n
+ __dict__ = property(_asdict) \n
def _replace(_self, **kwds):
'Return a new %(typename)s object replacing specified fields with new values'
result = _self._make(map(kwds.pop, %(field_names)r, _self))
diff --git a/Lib/compileall.py b/Lib/compileall.py
index 910f305..5cfa8be 100644
--- a/Lib/compileall.py
+++ b/Lib/compileall.py
@@ -1,4 +1,4 @@
-"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
+"""Module/script to byte-compile all .py files to .pyc (or .pyo) files.
When called as a script with arguments, this compiles the directories
given as arguments recursively; the -l option prevents it from
@@ -26,8 +26,8 @@
dir: the directory to byte-compile
maxlevels: maximum recursion level (default 10)
- ddir: if given, purported directory name (this is the
- directory name that will show up in error messages)
+ ddir: the directory that will be prepended to the path to the
+ file as it is compiled into each byte-code file.
force: if 1, force compilation, even if timestamps are up-to-date
quiet: if 1, be quiet during compilation
"""
@@ -64,8 +64,8 @@
Arguments (only fullname is required):
fullname: the file to byte-compile
- ddir: if given, purported directory name (this is the
- directory name that will show up in error messages)
+ ddir: if given, the directory name compiled in to the
+ byte-code file.
force: if 1, force compilation, even if timestamps are up-to-date
quiet: if 1, be quiet during compilation
"""
@@ -157,14 +157,27 @@
print msg
print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
"[-x regexp] [-i list] [directory|file ...]"
- print "-l: don't recurse down"
+ print
+ print "arguments: zero or more file and directory names to compile; " \
+ "if no arguments given, "
+ print " defaults to the equivalent of -l sys.path"
+ print
+ print "options:"
+ print "-l: don't recurse into subdirectories"
print "-f: force rebuild even if timestamps are up-to-date"
- print "-q: quiet operation"
- print "-d destdir: purported directory name for error messages"
- print " if no directory arguments, -l sys.path is assumed"
- print "-x regexp: skip files matching the regular expression regexp"
- print " the regexp is searched for in the full path of the file"
- print "-i list: expand list with its content (file and directory names)"
+ print "-q: output only error messages"
+ print "-d destdir: directory to prepend to file paths for use in " \
+ "compile-time tracebacks and in"
+ print " runtime tracebacks in cases where the source " \
+ "file is unavailable"
+ print "-x regexp: skip files matching the regular expression regexp; " \
+ "the regexp is searched for"
+ print " in the full path of each file considered for " \
+ "compilation"
+ print "-i file: add all the files and directories listed in file to " \
+ "the list considered for"
+ print ' compilation; if "-", names are read from stdin'
+
sys.exit(2)
maxlevels = 10
ddir = None
@@ -205,7 +218,7 @@
else:
success = compile_path()
except KeyboardInterrupt:
- print "\n[interrupt]"
+ print "\n[interrupted]"
success = 0
return success
diff --git a/Lib/ctypes/_endian.py b/Lib/ctypes/_endian.py
index 6de0d47..e6b8556 100644
--- a/Lib/ctypes/_endian.py
+++ b/Lib/ctypes/_endian.py
@@ -10,14 +10,18 @@
"""Return the type with the 'other' byte order. Simple types like
c_int and so on already have __ctype_be__ and __ctype_le__
attributes which contain the types, for more complicated types
- only arrays are supported.
+ arrays and structures are supported.
"""
- try:
+ # check _OTHER_ENDIAN attribute (present if typ is primitive type)
+ if hasattr(typ, _OTHER_ENDIAN):
return getattr(typ, _OTHER_ENDIAN)
- except AttributeError:
- if type(typ) == _array_type:
- return _other_endian(typ._type_) * typ._length_
- raise TypeError("This type does not support other endian: %s" % typ)
+ # if typ is array
+ if isinstance(typ, _array_type):
+ return _other_endian(typ._type_) * typ._length_
+ # if typ is structure
+ if issubclass(typ, Structure):
+ return typ
+ raise TypeError("This type does not support other endian: %s" % typ)
class _swapped_meta(type(Structure)):
def __setattr__(self, attrname, value):
diff --git a/Lib/ctypes/test/test_buffers.py b/Lib/ctypes/test/test_buffers.py
index bf931ab..12945ed 100644
--- a/Lib/ctypes/test/test_buffers.py
+++ b/Lib/ctypes/test/test_buffers.py
@@ -20,6 +20,10 @@
self.assertEqual(b[::2], "ac")
self.assertEqual(b[::5], "a")
+ def test_buffer_interface(self):
+ self.assertEqual(len(bytearray(create_string_buffer(0))), 0)
+ self.assertEqual(len(bytearray(create_string_buffer(1))), 1)
+
def test_string_conversion(self):
b = create_string_buffer(u"abc")
self.assertEqual(len(b), 4) # trailing nul char
diff --git a/Lib/ctypes/test/test_byteswap.py b/Lib/ctypes/test/test_byteswap.py
index 3163756..4bd75cd 100644
--- a/Lib/ctypes/test/test_byteswap.py
+++ b/Lib/ctypes/test/test_byteswap.py
@@ -1,4 +1,4 @@
-import sys, unittest, struct, math
+import sys, unittest, struct, math, ctypes
from binascii import hexlify
from ctypes import *
@@ -185,18 +185,32 @@
self.assertRaises(TypeError, setattr, T, "_fields_", [("x", typ)])
def test_struct_struct(self):
- # Nested structures with different byte order not (yet) supported
- if sys.byteorder == "little":
- base = BigEndianStructure
- else:
- base = LittleEndianStructure
+ # nested structures with different byteorders
- class T(Structure):
- _fields_ = [("a", c_int),
- ("b", c_int)]
- class S(base):
- pass
- self.assertRaises(TypeError, setattr, S, "_fields_", [("s", T)])
+ # create nested structures with given byteorders and set memory to data
+
+ for nested, data in (
+ (BigEndianStructure, b'\0\0\0\1\0\0\0\2'),
+ (LittleEndianStructure, b'\1\0\0\0\2\0\0\0'),
+ ):
+ for parent in (
+ BigEndianStructure,
+ LittleEndianStructure,
+ Structure,
+ ):
+ class NestedStructure(nested):
+ _fields_ = [("x", c_uint32),
+ ("y", c_uint32)]
+
+ class TestStructure(parent):
+ _fields_ = [("point", NestedStructure)]
+
+ self.assertEqual(len(data), sizeof(TestStructure))
+ ptr = POINTER(TestStructure)
+ s = cast(data, ptr)[0]
+ del ctypes._pointer_type_cache[TestStructure]
+ self.assertEqual(s.point.x, 1)
+ self.assertEqual(s.point.y, 2)
def test_struct_fields_2(self):
# standard packing in struct uses no alignment.
diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py
index 621a019..be0c17e 100644
--- a/Lib/ctypes/test/test_callbacks.py
+++ b/Lib/ctypes/test/test_callbacks.py
@@ -140,6 +140,14 @@
if isinstance(x, X)]
self.assertEqual(len(live), 0)
+ def test_issue12483(self):
+ import gc
+ class Nasty:
+ def __del__(self):
+ gc.collect()
+ CFUNCTYPE(None)(lambda x=Nasty(): None)
+
+
try:
WINFUNCTYPE
except NameError:
diff --git a/Lib/ctypes/test/test_structures.py b/Lib/ctypes/test/test_structures.py
index 77cfb26..1bde101 100644
--- a/Lib/ctypes/test/test_structures.py
+++ b/Lib/ctypes/test/test_structures.py
@@ -239,6 +239,14 @@
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
+ def test_invalid_name(self):
+ # field name must be string
+ def declare_with_name(name):
+ class S(Structure):
+ _fields_ = [(name, c_int)]
+
+ self.assertRaises(TypeError, declare_with_name, u"x\xe9")
+
def test_intarray_fields(self):
class SomeInts(Structure):
_fields_ = [("a", c_int * 4)]
@@ -324,6 +332,18 @@
else:
self.assertEqual(msg, "(Phone) exceptions.TypeError: too many initializers")
+ def test_huge_field_name(self):
+ # issue12881: segfault with large structure field names
+ def create_class(length):
+ class S(Structure):
+ _fields_ = [('x' * length, c_int)]
+
+ for length in [10 ** i for i in range(0, 8)]:
+ try:
+ create_class(length)
+ except MemoryError:
+ # MemoryErrors are OK, we just don't want to segfault
+ pass
def get_except(self, func, *args):
try:
diff --git a/Lib/decimal.py b/Lib/decimal.py
index 5470d00..3cb3b80 100644
--- a/Lib/decimal.py
+++ b/Lib/decimal.py
@@ -21,7 +21,7 @@
This is a Py2.3 implementation of decimal floating point arithmetic based on
the General Decimal Arithmetic Specification:
- www2.hursley.ibm.com/decimal/decarith.html
+ http://speleotrove.com/decimal/decarith.html
and IEEE standard 854-1987:
@@ -1942,9 +1942,9 @@
nonzero. For efficiency, other._exp should not be too large,
so that 10**abs(other._exp) is a feasible calculation."""
- # In the comments below, we write x for the value of self and
- # y for the value of other. Write x = xc*10**xe and y =
- # yc*10**ye.
+ # In the comments below, we write x for the value of self and y for the
+ # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
+ # and yc positive integers not divisible by 10.
# The main purpose of this method is to identify the *failure*
# of x**y to be exactly representable with as little effort as
@@ -1952,13 +1952,12 @@
# eliminate the possibility of x**y being exact. Only if all
# these tests are passed do we go on to actually compute x**y.
- # Here's the main idea. First normalize both x and y. We
- # express y as a rational m/n, with m and n relatively prime
- # and n>0. Then for x**y to be exactly representable (at
- # *any* precision), xc must be the nth power of a positive
- # integer and xe must be divisible by n. If m is negative
- # then additionally xc must be a power of either 2 or 5, hence
- # a power of 2**n or 5**n.
+ # Here's the main idea. Express y as a rational number m/n, with m and
+ # n relatively prime and n>0. Then for x**y to be exactly
+ # representable (at *any* precision), xc must be the nth power of a
+ # positive integer and xe must be divisible by n. If y is negative
+ # then additionally xc must be a power of either 2 or 5, hence a power
+ # of 2**n or 5**n.
#
# There's a limit to how small |y| can be: if y=m/n as above
# then:
@@ -2030,21 +2029,43 @@
return None
# now xc is a power of 2; e is its exponent
e = _nbits(xc)-1
- # find e*y and xe*y; both must be integers
- if ye >= 0:
- y_as_int = yc*10**ye
- e = e*y_as_int
- xe = xe*y_as_int
- else:
- ten_pow = 10**-ye
- e, remainder = divmod(e*yc, ten_pow)
- if remainder:
- return None
- xe, remainder = divmod(xe*yc, ten_pow)
- if remainder:
- return None
- if e*65 >= p*93: # 93/65 > log(10)/log(5)
+ # We now have:
+ #
+ # x = 2**e * 10**xe, e > 0, and y < 0.
+ #
+ # The exact result is:
+ #
+ # x**y = 5**(-e*y) * 10**(e*y + xe*y)
+ #
+ # provided that both e*y and xe*y are integers. Note that if
+ # 5**(-e*y) >= 10**p, then the result can't be expressed
+ # exactly with p digits of precision.
+ #
+ # Using the above, we can guard against large values of ye.
+ # 93/65 is an upper bound for log(10)/log(5), so if
+ #
+ # ye >= len(str(93*p//65))
+ #
+ # then
+ #
+ # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
+ #
+ # so 5**(-e*y) >= 10**p, and the coefficient of the result
+ # can't be expressed in p digits.
+
+ # emax >= largest e such that 5**e < 10**p.
+ emax = p*93//65
+ if ye >= len(str(emax)):
+ return None
+
+ # Find -e*y and -xe*y; both must be integers
+ e = _decimal_lshift_exact(e * yc, ye)
+ xe = _decimal_lshift_exact(xe * yc, ye)
+ if e is None or xe is None:
+ return None
+
+ if e > emax:
return None
xc = 5**e
@@ -2058,19 +2079,20 @@
while xc % 5 == 0:
xc //= 5
e -= 1
- if ye >= 0:
- y_as_integer = yc*10**ye
- e = e*y_as_integer
- xe = xe*y_as_integer
- else:
- ten_pow = 10**-ye
- e, remainder = divmod(e*yc, ten_pow)
- if remainder:
- return None
- xe, remainder = divmod(xe*yc, ten_pow)
- if remainder:
- return None
- if e*3 >= p*10: # 10/3 > log(10)/log(2)
+
+ # Guard against large values of ye, using the same logic as in
+ # the 'xc is a power of 2' branch. 10/3 is an upper bound for
+ # log(10)/log(2).
+ emax = p*10//3
+ if ye >= len(str(emax)):
+ return None
+
+ e = _decimal_lshift_exact(e * yc, ye)
+ xe = _decimal_lshift_exact(xe * yc, ye)
+ if e is None or xe is None:
+ return None
+
+ if e > emax:
return None
xc = 2**e
else:
@@ -5463,6 +5485,27 @@
hex_n = "%x" % n
return 4*len(hex_n) - correction[hex_n[0]]
+def _decimal_lshift_exact(n, e):
+ """ Given integers n and e, return n * 10**e if it's an integer, else None.
+
+ The computation is designed to avoid computing large powers of 10
+ unnecessarily.
+
+ >>> _decimal_lshift_exact(3, 4)
+ 30000
+ >>> _decimal_lshift_exact(300, -999999999) # returns None
+
+ """
+ if n == 0:
+ return 0
+ elif e >= 0:
+ return n * 10**e
+ else:
+ # val_n = largest power of 10 dividing n.
+ str_n = str(abs(n))
+ val_n = len(str_n) - len(str_n.rstrip('0'))
+ return None if val_n < -e else n // 10**-e
+
def _sqrt_nearest(n, a):
"""Closest integer to the square root of the positive integer n. a is
an initial approximation to the square root. Any positive integer
diff --git a/Lib/distutils/__init__.py b/Lib/distutils/__init__.py
index a82d4cb..a849f1a 100644
--- a/Lib/distutils/__init__.py
+++ b/Lib/distutils/__init__.py
@@ -15,5 +15,5 @@
# Updated automatically by the Python release process.
#
#--start constants--
-__version__ = "2.7.1"
+__version__ = "2.7.2"
#--end constants--
diff --git a/Lib/distutils/command/bdist_dumb.py b/Lib/distutils/command/bdist_dumb.py
index 7c60d39..2f3c668 100644
--- a/Lib/distutils/command/bdist_dumb.py
+++ b/Lib/distutils/command/bdist_dumb.py
@@ -58,7 +58,7 @@
self.format = None
self.keep_temp = 0
self.dist_dir = None
- self.skip_build = 0
+ self.skip_build = None
self.relative = 0
self.owner = None
self.group = None
@@ -78,7 +78,8 @@
self.set_undefined_options('bdist',
('dist_dir', 'dist_dir'),
- ('plat_name', 'plat_name'))
+ ('plat_name', 'plat_name'),
+ ('skip_build', 'skip_build'))
def run(self):
if not self.skip_build:
diff --git a/Lib/distutils/command/bdist_msi.py b/Lib/distutils/command/bdist_msi.py
index ded837d..703f873 100644
--- a/Lib/distutils/command/bdist_msi.py
+++ b/Lib/distutils/command/bdist_msi.py
@@ -131,18 +131,22 @@
self.no_target_optimize = 0
self.target_version = None
self.dist_dir = None
- self.skip_build = 0
+ self.skip_build = None
self.install_script = None
self.pre_install_script = None
self.versions = None
def finalize_options (self):
+ self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
+
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'msi')
+
short_version = get_python_version()
if (not self.target_version) and self.distribution.has_ext_modules():
self.target_version = short_version
+
if self.target_version:
self.versions = [self.target_version]
if not self.skip_build and self.distribution.has_ext_modules()\
diff --git a/Lib/distutils/command/bdist_wininst.py b/Lib/distutils/command/bdist_wininst.py
index 36d46bd..aa9383a 100644
--- a/Lib/distutils/command/bdist_wininst.py
+++ b/Lib/distutils/command/bdist_wininst.py
@@ -71,7 +71,7 @@
self.dist_dir = None
self.bitmap = None
self.title = None
- self.skip_build = 0
+ self.skip_build = None
self.install_script = None
self.pre_install_script = None
self.user_access_control = None
@@ -80,6 +80,8 @@
def finalize_options (self):
+ self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
+
if self.bdist_dir is None:
if self.skip_build and self.plat_name:
# If build is skipped and plat_name is overridden, bdist will
@@ -89,8 +91,10 @@
# next the command will be initialized using that name
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'wininst')
+
if not self.target_version:
self.target_version = ""
+
if not self.skip_build and self.distribution.has_ext_modules():
short_version = get_python_version()
if self.target_version and self.target_version != short_version:
diff --git a/Lib/distutils/command/check.py b/Lib/distutils/command/check.py
index bc29baa..4b64e45 100644
--- a/Lib/distutils/command/check.py
+++ b/Lib/distutils/command/check.py
@@ -5,6 +5,7 @@
__revision__ = "$Id$"
from distutils.core import Command
+from distutils.dist import PKG_INFO_ENCODING
from distutils.errors import DistutilsSetupError
try:
@@ -108,6 +109,8 @@
def check_restructuredtext(self):
"""Checks if the long string fields are reST-compliant."""
data = self.distribution.get_long_description()
+ if not isinstance(data, unicode):
+ data = data.decode(PKG_INFO_ENCODING)
for warning in self._check_rst_data(data):
line = warning[-1].get('line')
if line is None:
diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py
index dc08990..edb42b9 100644
--- a/Lib/distutils/command/register.py
+++ b/Lib/distutils/command/register.py
@@ -10,7 +10,6 @@
import urllib2
import getpass
import urlparse
-import StringIO
from warnings import warn
from distutils.core import PyPIRCCommand
@@ -260,21 +259,30 @@
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = '\n--' + boundary
end_boundary = sep_boundary + '--'
- body = StringIO.StringIO()
+ chunks = []
for key, value in data.items():
# handle multiple entries for the same name
if type(value) not in (type([]), type( () )):
value = [value]
for value in value:
- body.write(sep_boundary)
- body.write('\nContent-Disposition: form-data; name="%s"'%key)
- body.write("\n\n")
- body.write(value)
+ chunks.append(sep_boundary)
+ chunks.append('\nContent-Disposition: form-data; name="%s"'%key)
+ chunks.append("\n\n")
+ chunks.append(value)
if value and value[-1] == '\r':
- body.write('\n') # write an extra newline (lurve Macs)
- body.write(end_boundary)
- body.write("\n")
- body = body.getvalue()
+ chunks.append('\n') # write an extra newline (lurve Macs)
+ chunks.append(end_boundary)
+ chunks.append("\n")
+
+ # chunks may be bytes (str) or unicode objects that we need to encode
+ body = []
+ for chunk in chunks:
+ if isinstance(chunk, unicode):
+ body.append(chunk.encode('utf-8'))
+ else:
+ body.append(chunk)
+
+ body = ''.join(body)
# build the Request
headers = {
diff --git a/Lib/distutils/command/sdist.py b/Lib/distutils/command/sdist.py
index 0c3b0b5..d30de10 100644
--- a/Lib/distutils/command/sdist.py
+++ b/Lib/distutils/command/sdist.py
@@ -182,14 +182,20 @@
reading the manifest, or just using the default file set -- it all
depends on the user's options.
"""
- # new behavior:
+ # new behavior when using a template:
# the file list is recalculated everytime because
# even if MANIFEST.in or setup.py are not changed
# the user might have added some files in the tree that
# need to be included.
#
- # This makes --force the default and only behavior.
+ # This makes --force the default and only behavior with templates.
template_exists = os.path.isfile(self.template)
+ if not template_exists and self._manifest_is_not_generated():
+ self.read_manifest()
+ self.filelist.sort()
+ self.filelist.remove_duplicates()
+ return
+
if not template_exists:
self.warn(("manifest template '%s' does not exist " +
"(using default file list)") %
@@ -306,17 +312,23 @@
rstrip_ws=1,
collapse_join=1)
- while 1:
- line = template.readline()
- if line is None: # end of file
- break
+ try:
+ while 1:
+ line = template.readline()
+ if line is None: # end of file
+ break
- try:
- self.filelist.process_template_line(line)
- except DistutilsTemplateError, msg:
- self.warn("%s, line %d: %s" % (template.filename,
- template.current_line,
- msg))
+ try:
+ self.filelist.process_template_line(line)
+ # the call above can raise a DistutilsTemplateError for
+ # malformed lines, or a ValueError from the lower-level
+ # convert_path function
+ except (DistutilsTemplateError, ValueError) as msg:
+ self.warn("%s, line %d: %s" % (template.filename,
+ template.current_line,
+ msg))
+ finally:
+ template.close()
def prune_file_list(self):
"""Prune off branches that might slip into the file list as created
@@ -349,23 +361,28 @@
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'.
"""
- if os.path.isfile(self.manifest):
- fp = open(self.manifest)
- try:
- first_line = fp.readline()
- finally:
- fp.close()
-
- if first_line != '# file GENERATED by distutils, do NOT edit\n':
- log.info("not writing to manually maintained "
- "manifest file '%s'" % self.manifest)
- return
+ if self._manifest_is_not_generated():
+ log.info("not writing to manually maintained "
+ "manifest file '%s'" % self.manifest)
+ return
content = self.filelist.files[:]
content.insert(0, '# file GENERATED by distutils, do NOT edit')
self.execute(file_util.write_file, (self.manifest, content),
"writing manifest file '%s'" % self.manifest)
+ def _manifest_is_not_generated(self):
+ # check for special comment used in 2.7.1 and higher
+ if not os.path.isfile(self.manifest):
+ return False
+
+ fp = open(self.manifest, 'rU')
+ try:
+ first_line = fp.readline()
+ finally:
+ fp.close()
+ return first_line != '# file GENERATED by distutils, do NOT edit\n'
+
def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and use it to
fill in 'self.filelist', the list of files to include in the source
@@ -373,12 +390,11 @@
"""
log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest)
- while 1:
- line = manifest.readline()
- if line == '': # end of file
- break
- if line[-1] == '\n':
- line = line[0:-1]
+ for line in manifest:
+ # ignore comments and blank lines
+ line = line.strip()
+ if line.startswith('#') or not line:
+ continue
self.filelist.append(line)
manifest.close()
diff --git a/Lib/distutils/dep_util.py b/Lib/distutils/dep_util.py
index 4e40df6..2b75905 100644
--- a/Lib/distutils/dep_util.py
+++ b/Lib/distutils/dep_util.py
@@ -7,6 +7,7 @@
__revision__ = "$Id$"
import os
+from stat import ST_MTIME
from distutils.errors import DistutilsFileError
def newer(source, target):
@@ -27,7 +28,7 @@
if not os.path.exists(target):
return True
- return os.stat(source).st_mtime > os.stat(target).st_mtime
+ return os.stat(source)[ST_MTIME] > os.stat(target)[ST_MTIME]
def newer_pairwise(sources, targets):
"""Walk two filename lists in parallel, testing if each source is newer
@@ -71,7 +72,7 @@
# is more recent than 'target', then 'target' is out-of-date and
# we can immediately return true. If we fall through to the end
# of the loop, then 'target' is up-to-date and we return false.
- target_mtime = os.stat(target).st_mtime
+ target_mtime = os.stat(target)[ST_MTIME]
for source in sources:
if not os.path.exists(source):
@@ -82,7 +83,7 @@
elif missing == 'newer': # missing source means target is
return True # out-of-date
- if os.stat(source).st_mtime > target_mtime:
+ if os.stat(source)[ST_MTIME] > target_mtime:
return True
return False
diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py
index 597909e..e025313 100644
--- a/Lib/distutils/dist.py
+++ b/Lib/distutils/dist.py
@@ -1111,7 +1111,8 @@
"""Write the PKG-INFO format data to a file object.
"""
version = '1.0'
- if self.provides or self.requires or self.obsoletes:
+ if (self.provides or self.requires or self.obsoletes or
+ self.classifiers or self.download_url):
version = '1.1'
self._write_field(file, 'Metadata-Version', version)
diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py
index 5c014c4..7306099 100644
--- a/Lib/distutils/spawn.py
+++ b/Lib/distutils/spawn.py
@@ -96,17 +96,43 @@
raise DistutilsExecError, \
"command '%s' failed with exit status %d" % (cmd[0], rc)
+if sys.platform == 'darwin':
+ from distutils import sysconfig
+ _cfg_target = None
+ _cfg_target_split = None
def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
log.info(' '.join(cmd))
if dry_run:
return
exec_fn = search_path and os.execvp or os.execv
+ exec_args = [cmd[0], cmd]
+ if sys.platform == 'darwin':
+ global _cfg_target, _cfg_target_split
+ if _cfg_target is None:
+ _cfg_target = sysconfig.get_config_var(
+ 'MACOSX_DEPLOYMENT_TARGET') or ''
+ if _cfg_target:
+ _cfg_target_split = [int(x) for x in _cfg_target.split('.')]
+ if _cfg_target:
+ # ensure that the deployment target of build process is not less
+ # than that used when the interpreter was built. This ensures
+ # extension modules are built with correct compatibility values
+ cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target)
+ if _cfg_target_split > [int(x) for x in cur_target.split('.')]:
+ my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: '
+ 'now "%s" but "%s" during configure'
+ % (cur_target, _cfg_target))
+ raise DistutilsPlatformError(my_msg)
+ env = dict(os.environ,
+ MACOSX_DEPLOYMENT_TARGET=cur_target)
+ exec_fn = search_path and os.execvpe or os.execve
+ exec_args.append(env)
pid = os.fork()
if pid == 0: # in the child
try:
- exec_fn(cmd[0], cmd)
+ exec_fn(*exec_args)
except OSError, e:
sys.stderr.write("unable to execute %s: %s\n" %
(cmd[0], e.strerror))
diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py
index 33cc5a3..0d6d4c4 100644
--- a/Lib/distutils/sysconfig.py
+++ b/Lib/distutils/sysconfig.py
@@ -380,21 +380,6 @@
raise DistutilsPlatformError(my_msg)
- # On MacOSX we need to check the setting of the environment variable
- # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
- # it needs to be compatible.
- # If it isn't set we set it to the configure-time value
- if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
- cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
- cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
- if cur_target == '':
- cur_target = cfg_target
- os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
- elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
- my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
- % (cur_target, cfg_target))
- raise DistutilsPlatformError(my_msg)
-
# On AIX, there are wrong paths to the linker scripts in the Makefile
# -- these paths are relative to the Python source, but when installed
# the scripts are in another directory.
diff --git a/Lib/distutils/tests/Setup.sample b/Lib/distutils/tests/Setup.sample
old mode 100755
new mode 100644
diff --git a/Lib/distutils/tests/support.py b/Lib/distutils/tests/support.py
index 783318e..a2190c0 100644
--- a/Lib/distutils/tests/support.py
+++ b/Lib/distutils/tests/support.py
@@ -1,7 +1,10 @@
"""Support code for distutils test cases."""
import os
+import sys
import shutil
import tempfile
+import unittest
+import sysconfig
from copy import deepcopy
import warnings
@@ -9,6 +12,7 @@
from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
from distutils.core import Distribution
+
def capture_warnings(func):
def _capture_warnings(*args, **kw):
with warnings.catch_warnings():
@@ -16,6 +20,7 @@
return func(*args, **kw)
return _capture_warnings
+
class LoggingSilencer(object):
def setUp(self):
@@ -49,6 +54,7 @@
def clear_logs(self):
self.logs = []
+
class TempdirManager(object):
"""Mix-in class that handles temporary directories for test cases.
@@ -57,9 +63,13 @@
def setUp(self):
super(TempdirManager, self).setUp()
+ self.old_cwd = os.getcwd()
self.tempdirs = []
def tearDown(self):
+ # Restore working dir, for Solaris and derivatives, where rmdir()
+ # on the current directory fails.
+ os.chdir(self.old_cwd)
super(TempdirManager, self).tearDown()
while self.tempdirs:
d = self.tempdirs.pop()
@@ -105,6 +115,7 @@
return pkg_dir, dist
+
class DummyCommand:
"""Class to store options for retrieval via set_undefined_options()."""
@@ -115,6 +126,7 @@
def ensure_finalized(self):
pass
+
class EnvironGuard(object):
def setUp(self):
@@ -131,3 +143,73 @@
del os.environ[key]
super(EnvironGuard, self).tearDown()
+
+
+def copy_xxmodule_c(directory):
+ """Helper for tests that need the xxmodule.c source file.
+
+ Example use:
+
+ def test_compile(self):
+ copy_xxmodule_c(self.tmpdir)
+ self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
+
+ If the source file can be found, it will be copied to *directory*. If not,
+ the test will be skipped. Errors during copy are not caught.
+ """
+ filename = _get_xxmodule_path()
+ if filename is None:
+ raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
+ 'the python build dir)')
+ shutil.copy(filename, directory)
+
+
+def _get_xxmodule_path():
+ # FIXME when run from regrtest, srcdir seems to be '.', which does not help
+ # us find the xxmodule.c file
+ srcdir = sysconfig.get_config_var('srcdir')
+ candidates = [
+ # use installed copy if available
+ os.path.join(os.path.dirname(__file__), 'xxmodule.c'),
+ # otherwise try using copy from build directory
+ os.path.join(srcdir, 'Modules', 'xxmodule.c'),
+ # srcdir mysteriously can be $srcdir/Lib/distutils/tests when
+ # this file is run from its parent directory, so walk up the
+ # tree to find the real srcdir
+ os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'),
+ ]
+ for path in candidates:
+ if os.path.exists(path):
+ return path
+
+
+def fixup_build_ext(cmd):
+ """Function needed to make build_ext tests pass.
+
+ When Python was build with --enable-shared on Unix, -L. is not good
+ enough to find the libpython<blah>.so. This is because regrtest runs
+ it under a tempdir, not in the top level where the .so lives. By the
+ time we've gotten here, Python's already been chdir'd to the tempdir.
+
+ When Python was built with in debug mode on Windows, build_ext commands
+ need their debug attribute set, and it is not done automatically for
+ some reason.
+
+ This function handles both of these things. Example use:
+
+ cmd = build_ext(dist)
+ support.fixup_build_ext(cmd)
+ cmd.ensure_finalized()
+ """
+ if os.name == 'nt':
+ cmd.debug = sys.executable.endswith('_d.exe')
+ elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
+ # To further add to the shared builds fun on Unix, we can't just add
+ # library_dirs to the Extension() instance because that doesn't get
+ # plumbed through to the final compiler command.
+ runshared = sysconfig.get_config_var('RUNSHARED')
+ if runshared is None:
+ cmd.library_dirs = ['.']
+ else:
+ name, equals, value = runshared.partition('=')
+ cmd.library_dirs = value.split(os.pathsep)
diff --git a/Lib/distutils/tests/test_bdist.py b/Lib/distutils/tests/test_bdist.py
index fa7cd5a..121d099 100644
--- a/Lib/distutils/tests/test_bdist.py
+++ b/Lib/distutils/tests/test_bdist.py
@@ -1,42 +1,49 @@
"""Tests for distutils.command.bdist."""
-import unittest
-import sys
import os
-import tempfile
-import shutil
+import unittest
from test.test_support import run_unittest
-from distutils.core import Distribution
from distutils.command.bdist import bdist
from distutils.tests import support
-from distutils.spawn import find_executable
-from distutils import spawn
-from distutils.errors import DistutilsExecError
+
class BuildTestCase(support.TempdirManager,
unittest.TestCase):
def test_formats(self):
-
# let's create a command and make sure
- # we can fix the format
- pkg_pth, dist = self.create_dist()
+ # we can set the format
+ dist = self.create_dist()[1]
cmd = bdist(dist)
cmd.formats = ['msi']
cmd.ensure_finalized()
self.assertEqual(cmd.formats, ['msi'])
- # what format bdist offers ?
- # XXX an explicit list in bdist is
- # not the best way to bdist_* commands
- # we should add a registry
- formats = ['rpm', 'zip', 'gztar', 'bztar', 'ztar',
- 'tar', 'wininst', 'msi']
- formats.sort()
- founded = cmd.format_command.keys()
- founded.sort()
- self.assertEqual(founded, formats)
+ # what formats does bdist offer?
+ formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar',
+ 'wininst', 'zip', 'ztar']
+ found = sorted(cmd.format_command)
+ self.assertEqual(found, formats)
+
+ def test_skip_build(self):
+ # bug #10946: bdist --skip-build should trickle down to subcommands
+ dist = self.create_dist()[1]
+ cmd = bdist(dist)
+ cmd.skip_build = 1
+ cmd.ensure_finalized()
+ dist.command_obj['bdist'] = cmd
+
+ names = ['bdist_dumb', 'bdist_wininst']
+ # bdist_rpm does not support --skip-build
+ if os.name == 'nt':
+ names.append('bdist_msi')
+
+ for name in names:
+ subcmd = cmd.get_finalized_command(name)
+ self.assertTrue(subcmd.skip_build,
+ '%s should take --skip-build from bdist' % name)
+
def test_suite():
return unittest.makeSuite(BuildTestCase)
diff --git a/Lib/distutils/tests/test_build_ext.py b/Lib/distutils/tests/test_build_ext.py
index 86568eb..2fa63d3 100644
--- a/Lib/distutils/tests/test_build_ext.py
+++ b/Lib/distutils/tests/test_build_ext.py
@@ -1,14 +1,14 @@
import sys
import os
-import tempfile
-import shutil
from StringIO import StringIO
+import textwrap
from distutils.core import Extension, Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
from distutils.tests import support
-from distutils.errors import DistutilsSetupError
+from distutils.errors import (DistutilsSetupError, CompileError,
+ DistutilsPlatformError)
import unittest
from test import test_support
@@ -17,71 +17,40 @@
# Don't load the xx module more than once.
ALREADY_TESTED = False
-def _get_source_filename():
- srcdir = sysconfig.get_config_var('srcdir')
- if srcdir is None:
- return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
- return os.path.join(srcdir, 'Modules', 'xxmodule.c')
-
-_XX_MODULE_PATH = _get_source_filename()
class BuildExtTestCase(support.TempdirManager,
support.LoggingSilencer,
unittest.TestCase):
def setUp(self):
- # Create a simple test environment
- # Note that we're making changes to sys.path
super(BuildExtTestCase, self).setUp()
- self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")
- if os.path.exists(_XX_MODULE_PATH):
- self.sys_path = sys.path[:]
- sys.path.append(self.tmp_dir)
- shutil.copy(_XX_MODULE_PATH, self.tmp_dir)
+ self.tmp_dir = self.mkdtemp()
+ self.xx_created = False
+ sys.path.append(self.tmp_dir)
+ self.addCleanup(sys.path.remove, self.tmp_dir)
+ if sys.version > "2.6":
+ import site
+ self.old_user_base = site.USER_BASE
+ site.USER_BASE = self.mkdtemp()
+ from distutils.command import build_ext
+ build_ext.USER_BASE = site.USER_BASE
def tearDown(self):
- # Get everything back to normal
- if os.path.exists(_XX_MODULE_PATH):
+ if self.xx_created:
test_support.unload('xx')
- sys.path[:] = self.sys_path
# XXX on Windows the test leaves a directory
# with xx module in TEMP
- shutil.rmtree(self.tmp_dir, os.name == 'nt' or
- sys.platform == 'cygwin')
super(BuildExtTestCase, self).tearDown()
- def _fixup_command(self, cmd):
- # When Python was build with --enable-shared, -L. is not good enough
- # to find the libpython<blah>.so. This is because regrtest runs it
- # under a tempdir, not in the top level where the .so lives. By the
- # time we've gotten here, Python's already been chdir'd to the
- # tempdir.
- #
- # To further add to the fun, we can't just add library_dirs to the
- # Extension() instance because that doesn't get plumbed through to the
- # final compiler command.
- if (sysconfig.get_config_var('Py_ENABLE_SHARED') and
- not sys.platform.startswith('win')):
- runshared = sysconfig.get_config_var('RUNSHARED')
- if runshared is None:
- cmd.library_dirs = ['.']
- else:
- name, equals, value = runshared.partition('=')
- cmd.library_dirs = value.split(os.pathsep)
-
- @unittest.skipIf(not os.path.exists(_XX_MODULE_PATH),
- 'xxmodule.c not found')
def test_build_ext(self):
global ALREADY_TESTED
+ support.copy_xxmodule_c(self.tmp_dir)
+ self.xx_created = True
xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
xx_ext = Extension('xx', [xx_c])
dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
dist.package_dir = self.tmp_dir
cmd = build_ext(dist)
- self._fixup_command(cmd)
- if os.name == "nt":
- # On Windows, we must build a debug version iff running
- # a debug build of Python
- cmd.debug = sys.executable.endswith("_d.exe")
+ support.fixup_build_ext(cmd)
cmd.build_lib = self.tmp_dir
cmd.build_temp = self.tmp_dir
@@ -134,6 +103,36 @@
# make sure we get some library dirs under solaris
self.assertTrue(len(cmd.library_dirs) > 0)
+ def test_user_site(self):
+ # site.USER_SITE was introduced in 2.6
+ if sys.version < '2.6':
+ return
+
+ import site
+ dist = Distribution({'name': 'xx'})
+ cmd = build_ext(dist)
+
+ # making sure the user option is there
+ options = [name for name, short, label in
+ cmd.user_options]
+ self.assertIn('user', options)
+
+ # setting a value
+ cmd.user = 1
+
+ # setting user based lib and include
+ lib = os.path.join(site.USER_BASE, 'lib')
+ incl = os.path.join(site.USER_BASE, 'include')
+ os.mkdir(lib)
+ os.mkdir(incl)
+
+ cmd.ensure_finalized()
+
+ # see if include_dirs and library_dirs were set
+ self.assertIn(lib, cmd.library_dirs)
+ self.assertIn(lib, cmd.rpath)
+ self.assertIn(incl, cmd.include_dirs)
+
def test_finalize_options(self):
# Make sure Python's include directories (for Python.h, pyconfig.h,
# etc.) are in the include search path.
@@ -142,7 +141,6 @@
cmd = build_ext(dist)
cmd.finalize_options()
- from distutils import sysconfig
py_include = sysconfig.get_python_inc()
self.assertTrue(py_include in cmd.include_dirs)
@@ -270,13 +268,10 @@
dist = Distribution({'name': 'xx',
'ext_modules': [ext]})
cmd = build_ext(dist)
- self._fixup_command(cmd)
+ support.fixup_build_ext(cmd)
cmd.ensure_finalized()
self.assertEqual(len(cmd.get_outputs()), 1)
- if os.name == "nt":
- cmd.debug = sys.executable.endswith("_d.exe")
-
cmd.build_lib = os.path.join(self.tmp_dir, 'build')
cmd.build_temp = os.path.join(self.tmp_dir, 'tempt')
@@ -430,6 +425,83 @@
wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext)
self.assertEqual(ext_path, wanted)
+ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
+ def test_deployment_target_default(self):
+ # Issue 9516: Test that, in the absence of the environment variable,
+ # an extension module is compiled with the same deployment target as
+ # the interpreter.
+ self._try_compile_deployment_target('==', None)
+
+ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
+ def test_deployment_target_too_low(self):
+ # Issue 9516: Test that an extension module is not allowed to be
+ # compiled with a deployment target less than that of the interpreter.
+ self.assertRaises(DistutilsPlatformError,
+ self._try_compile_deployment_target, '>', '10.1')
+
+ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
+ def test_deployment_target_higher_ok(self):
+ # Issue 9516: Test that an extension module can be compiled with a
+ # deployment target higher than that of the interpreter: the ext
+ # module may depend on some newer OS feature.
+ deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
+ if deptarget:
+ # increment the minor version number (i.e. 10.6 -> 10.7)
+ deptarget = [int(x) for x in deptarget.split('.')]
+ deptarget[-1] += 1
+ deptarget = '.'.join(str(i) for i in deptarget)
+ self._try_compile_deployment_target('<', deptarget)
+
+ def _try_compile_deployment_target(self, operator, target):
+ orig_environ = os.environ
+ os.environ = orig_environ.copy()
+ self.addCleanup(setattr, os, 'environ', orig_environ)
+
+ if target is None:
+ if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
+ del os.environ['MACOSX_DEPLOYMENT_TARGET']
+ else:
+ os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
+
+ deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
+
+ with open(deptarget_c, 'w') as fp:
+ fp.write(textwrap.dedent('''\
+ #include <AvailabilityMacros.h>
+
+ int dummy;
+
+ #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED
+ #else
+ #error "Unexpected target"
+ #endif
+
+ ''' % operator))
+
+ # get the deployment target that the interpreter was built with
+ target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
+ target = tuple(map(int, target.split('.')))
+ target = '%02d%01d0' % target
+ deptarget_ext = Extension(
+ 'deptarget',
+ [deptarget_c],
+ extra_compile_args=['-DTARGET=%s'%(target,)],
+ )
+ dist = Distribution({
+ 'name': 'deptarget',
+ 'ext_modules': [deptarget_ext]
+ })
+ dist.package_dir = self.tmp_dir
+ cmd = build_ext(dist)
+ cmd.build_lib = self.tmp_dir
+ cmd.build_temp = self.tmp_dir
+
+ try:
+ cmd.ensure_finalized()
+ cmd.run()
+ except CompileError:
+ self.fail("Wrong deployment target during compilation")
+
def test_suite():
return unittest.makeSuite(BuildExtTestCase)
diff --git a/Lib/distutils/tests/test_build_py.py b/Lib/distutils/tests/test_build_py.py
index 937fa0c..6c6ec20 100644
--- a/Lib/distutils/tests/test_build_py.py
+++ b/Lib/distutils/tests/test_build_py.py
@@ -17,7 +17,7 @@
support.LoggingSilencer,
unittest.TestCase):
- def _setup_package_data(self):
+ def test_package_data(self):
sources = self.mkdtemp()
f = open(os.path.join(sources, "__init__.py"), "w")
try:
@@ -57,20 +57,15 @@
self.assertEqual(len(cmd.get_outputs()), 3)
pkgdest = os.path.join(destination, "pkg")
files = os.listdir(pkgdest)
- return files
+ self.assertIn("__init__.py", files)
+ self.assertIn("README.txt", files)
+ # XXX even with -O, distutils writes pyc, not pyo; bug?
+ if sys.dont_write_bytecode:
+ self.assertNotIn("__init__.pyc", files)
+ else:
+ self.assertIn("__init__.pyc", files)
- def test_package_data(self):
- files = self._setup_package_data()
- self.assertTrue("__init__.py" in files)
- self.assertTrue("README.txt" in files)
-
- @unittest.skipIf(sys.flags.optimize >= 2,
- "pyc files are not written with -O2 and above")
- def test_package_data_pyc(self):
- files = self._setup_package_data()
- self.assertTrue("__init__.pyc" in files)
-
- def test_empty_package_dir (self):
+ def test_empty_package_dir(self):
# See SF 1668596/1720897.
cwd = os.getcwd()
@@ -118,7 +113,7 @@
finally:
sys.dont_write_bytecode = old_dont_write_bytecode
- self.assertTrue('byte-compiling is disabled' in self.logs[0][1])
+ self.assertIn('byte-compiling is disabled', self.logs[0][1])
def test_suite():
return unittest.makeSuite(BuildPyTestCase)
diff --git a/Lib/distutils/tests/test_check.py b/Lib/distutils/tests/test_check.py
index 4ea83dc..f73342a 100644
--- a/Lib/distutils/tests/test_check.py
+++ b/Lib/distutils/tests/test_check.py
@@ -1,3 +1,4 @@
+# -*- encoding: utf8 -*-
"""Tests for distutils.command.check."""
import unittest
from test.test_support import run_unittest
@@ -46,6 +47,15 @@
cmd = self._run(metadata, strict=1)
self.assertEqual(cmd._warnings, 0)
+ # now a test with Unicode entries
+ metadata = {'url': u'xxx', 'author': u'\u00c9ric',
+ 'author_email': u'xxx', u'name': 'xxx',
+ 'version': u'xxx',
+ 'description': u'Something about esszet \u00df',
+ 'long_description': u'More things about esszet \u00df'}
+ cmd = self._run(metadata)
+ self.assertEqual(cmd._warnings, 0)
+
def test_check_document(self):
if not HAS_DOCUTILS: # won't test without docutils
return
@@ -80,8 +90,8 @@
self.assertRaises(DistutilsSetupError, self._run, metadata,
**{'strict': 1, 'restructuredtext': 1})
- # and non-broken rest
- metadata['long_description'] = 'title\n=====\n\ntest'
+ # and non-broken rest, including a non-ASCII character to test #12114
+ metadata['long_description'] = u'title\n=====\n\ntest \u00df'
cmd = self._run(metadata, strict=1, restructuredtext=1)
self.assertEqual(cmd._warnings, 0)
diff --git a/Lib/distutils/tests/test_config_cmd.py b/Lib/distutils/tests/test_config_cmd.py
index a36a1d5..2cf3886 100644
--- a/Lib/distutils/tests/test_config_cmd.py
+++ b/Lib/distutils/tests/test_config_cmd.py
@@ -44,10 +44,10 @@
cmd = config(dist)
# simple pattern searches
- match = cmd.search_cpp(pattern='xxx', body='// xxx')
+ match = cmd.search_cpp(pattern='xxx', body='/* xxx */')
self.assertEqual(match, 0)
- match = cmd.search_cpp(pattern='_configtest', body='// xxx')
+ match = cmd.search_cpp(pattern='_configtest', body='/* xxx */')
self.assertEqual(match, 1)
def test_finalize_options(self):
diff --git a/Lib/distutils/tests/test_dist.py b/Lib/distutils/tests/test_dist.py
index ba60638..4b7bbeb 100644
--- a/Lib/distutils/tests/test_dist.py
+++ b/Lib/distutils/tests/test_dist.py
@@ -8,12 +8,13 @@
import warnings
import textwrap
-from distutils.dist import Distribution, fix_help_options, DistributionMetadata
+from distutils.dist import Distribution, fix_help_options
from distutils.cmd import Command
import distutils.dist
from test.test_support import TESTFN, captured_stdout, run_unittest
from distutils.tests import support
+
class test_dist(Command):
"""Sample distutils extension command."""
@@ -61,7 +62,7 @@
def test_debug_mode(self):
with open(TESTFN, "w") as f:
- f.write("[global]")
+ f.write("[global]\n")
f.write("command_packages = foo.bar, splat")
files = [TESTFN]
@@ -97,7 +98,7 @@
self.assertEqual(d.get_command_packages(),
["distutils.command", "foo.bar", "distutils.tests"])
cmd = d.get_command_obj("test_dist")
- self.assertTrue(isinstance(cmd, test_dist))
+ self.assertIsInstance(cmd, test_dist)
self.assertEqual(cmd.sample_option, "sometext")
def test_command_packages_configfile(self):
@@ -105,8 +106,8 @@
self.addCleanup(os.unlink, TESTFN)
f = open(TESTFN, "w")
try:
- print >>f, "[global]"
- print >>f, "command_packages = foo.bar, splat"
+ print >> f, "[global]"
+ print >> f, "command_packages = foo.bar, splat"
finally:
f.close()
@@ -138,7 +139,6 @@
'description': u'Café torréfié',
'long_description': u'Héhéhé'})
-
# let's make sure the file can be written
# with Unicode fields. they are encoded with
# PKG_INFO_ENCODING
@@ -152,33 +152,28 @@
'long_description': 'Hehehe'})
my_file2 = os.path.join(tmp_dir, 'f2')
- dist.metadata.write_pkg_file(open(my_file, 'w'))
+ dist.metadata.write_pkg_file(open(my_file2, 'w'))
def test_empty_options(self):
# an empty options dictionary should not stay in the
# list of attributes
- klass = Distribution
# catching warnings
warns = []
+
def _warn(msg):
warns.append(msg)
- old_warn = warnings.warn
+ self.addCleanup(setattr, warnings, 'warn', warnings.warn)
warnings.warn = _warn
- try:
- dist = klass(attrs={'author': 'xxx',
- 'name': 'xxx',
- 'version': 'xxx',
- 'url': 'xxxx',
- 'options': {}})
- finally:
- warnings.warn = old_warn
+ dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx',
+ 'version': 'xxx', 'url': 'xxxx',
+ 'options': {}})
self.assertEqual(len(warns), 0)
+ self.assertNotIn('options', dir(dist))
def test_finalize_options(self):
-
attrs = {'keywords': 'one,two',
'platforms': 'one,two'}
@@ -201,7 +196,6 @@
cmds = dist.get_command_packages()
self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
-
def test_announce(self):
# make sure the level is known
dist = Distribution()
@@ -251,15 +245,44 @@
sys.argv[:] = self.argv[1]
super(MetadataTestCase, self).tearDown()
+ def test_classifier(self):
+ attrs = {'name': 'Boa', 'version': '3.0',
+ 'classifiers': ['Programming Language :: Python :: 3']}
+ dist = Distribution(attrs)
+ meta = self.format_metadata(dist)
+ self.assertIn('Metadata-Version: 1.1', meta)
+
+ def test_download_url(self):
+ attrs = {'name': 'Boa', 'version': '3.0',
+ 'download_url': 'http://example.org/boa'}
+ dist = Distribution(attrs)
+ meta = self.format_metadata(dist)
+ self.assertIn('Metadata-Version: 1.1', meta)
+
+ def test_long_description(self):
+ long_desc = textwrap.dedent("""\
+ example::
+ We start here
+ and continue here
+ and end here.""")
+ attrs = {"name": "package",
+ "version": "1.0",
+ "long_description": long_desc}
+
+ dist = Distribution(attrs)
+ meta = self.format_metadata(dist)
+ meta = meta.replace('\n' + 8 * ' ', '\n')
+ self.assertIn(long_desc, meta)
+
def test_simple_metadata(self):
attrs = {"name": "package",
"version": "1.0"}
dist = Distribution(attrs)
meta = self.format_metadata(dist)
- self.assertTrue("Metadata-Version: 1.0" in meta)
- self.assertTrue("provides:" not in meta.lower())
- self.assertTrue("requires:" not in meta.lower())
- self.assertTrue("obsoletes:" not in meta.lower())
+ self.assertIn("Metadata-Version: 1.0", meta)
+ self.assertNotIn("provides:", meta.lower())
+ self.assertNotIn("requires:", meta.lower())
+ self.assertNotIn("obsoletes:", meta.lower())
def test_provides(self):
attrs = {"name": "package",
@@ -271,9 +294,9 @@
self.assertEqual(dist.get_provides(),
["package", "package.sub"])
meta = self.format_metadata(dist)
- self.assertTrue("Metadata-Version: 1.1" in meta)
- self.assertTrue("requires:" not in meta.lower())
- self.assertTrue("obsoletes:" not in meta.lower())
+ self.assertIn("Metadata-Version: 1.1", meta)
+ self.assertNotIn("requires:", meta.lower())
+ self.assertNotIn("obsoletes:", meta.lower())
def test_provides_illegal(self):
self.assertRaises(ValueError, Distribution,
@@ -291,11 +314,11 @@
self.assertEqual(dist.get_requires(),
["other", "another (==1.0)"])
meta = self.format_metadata(dist)
- self.assertTrue("Metadata-Version: 1.1" in meta)
- self.assertTrue("provides:" not in meta.lower())
- self.assertTrue("Requires: other" in meta)
- self.assertTrue("Requires: another (==1.0)" in meta)
- self.assertTrue("obsoletes:" not in meta.lower())
+ self.assertIn("Metadata-Version: 1.1", meta)
+ self.assertNotIn("provides:", meta.lower())
+ self.assertIn("Requires: other", meta)
+ self.assertIn("Requires: another (==1.0)", meta)
+ self.assertNotIn("obsoletes:", meta.lower())
def test_requires_illegal(self):
self.assertRaises(ValueError, Distribution,
@@ -313,11 +336,11 @@
self.assertEqual(dist.get_obsoletes(),
["other", "another (<1.0)"])
meta = self.format_metadata(dist)
- self.assertTrue("Metadata-Version: 1.1" in meta)
- self.assertTrue("provides:" not in meta.lower())
- self.assertTrue("requires:" not in meta.lower())
- self.assertTrue("Obsoletes: other" in meta)
- self.assertTrue("Obsoletes: another (<1.0)" in meta)
+ self.assertIn("Metadata-Version: 1.1", meta)
+ self.assertNotIn("provides:", meta.lower())
+ self.assertNotIn("requires:", meta.lower())
+ self.assertIn("Obsoletes: other", meta)
+ self.assertIn("Obsoletes: another (<1.0)", meta)
def test_obsoletes_illegal(self):
self.assertRaises(ValueError, Distribution,
@@ -353,14 +376,14 @@
if sys.platform in ('linux', 'darwin'):
os.environ['HOME'] = temp_dir
files = dist.find_config_files()
- self.assertTrue(user_filename in files)
+ self.assertIn(user_filename, files)
# win32-style
if sys.platform == 'win32':
# home drive should be found
os.environ['HOME'] = temp_dir
files = dist.find_config_files()
- self.assertTrue(user_filename in files,
+ self.assertIn(user_filename, files,
'%r not found in %r' % (user_filename, files))
finally:
os.remove(user_filename)
@@ -382,22 +405,7 @@
output = [line for line in s.getvalue().split('\n')
if line.strip() != '']
- self.assertTrue(len(output) > 0)
-
- def test_long_description(self):
- long_desc = textwrap.dedent("""\
- example::
- We start here
- and continue here
- and end here.""")
- attrs = {"name": "package",
- "version": "1.0",
- "long_description": long_desc}
-
- dist = distutils.dist.Distribution(attrs)
- meta = self.format_metadata(dist)
- meta = meta.replace('\n' + 8 * ' ', '\n')
- self.assertTrue(long_desc in meta)
+ self.assertTrue(output)
def test_read_metadata(self):
attrs = {"name": "package",
@@ -426,6 +434,7 @@
self.assertEqual(metadata.obsoletes, None)
self.assertEqual(metadata.requires, ['foo'])
+
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(DistributionTestCase))
diff --git a/Lib/distutils/tests/test_install.py b/Lib/distutils/tests/test_install.py
index 4f976f3..ebfb04f 100644
--- a/Lib/distutils/tests/test_install.py
+++ b/Lib/distutils/tests/test_install.py
@@ -1,17 +1,33 @@
"""Tests for distutils.command.install."""
import os
+import sys
import unittest
+import site
-from test.test_support import run_unittest
+from test.test_support import captured_stdout, run_unittest
+from distutils import sysconfig
from distutils.command.install import install
+from distutils.command import install as install_module
+from distutils.command.build_ext import build_ext
+from distutils.command.install import INSTALL_SCHEMES
from distutils.core import Distribution
+from distutils.errors import DistutilsOptionError
+from distutils.extension import Extension
from distutils.tests import support
-class InstallTestCase(support.TempdirManager, unittest.TestCase):
+def _make_ext_name(modname):
+ if os.name == 'nt' and sys.executable.endswith('_d.exe'):
+ modname += '_d'
+ return modname + sysconfig.get_config_var('SO')
+
+
+class InstallTestCase(support.TempdirManager,
+ support.LoggingSilencer,
+ unittest.TestCase):
def test_home_installation_scheme(self):
# This ensure two things:
@@ -49,6 +65,181 @@
check_path(cmd.install_scripts, os.path.join(destination, "bin"))
check_path(cmd.install_data, destination)
+ def test_user_site(self):
+ # site.USER_SITE was introduced in 2.6
+ if sys.version < '2.6':
+ return
+
+ # preparing the environment for the test
+ self.old_user_base = site.USER_BASE
+ self.old_user_site = site.USER_SITE
+ self.tmpdir = self.mkdtemp()
+ self.user_base = os.path.join(self.tmpdir, 'B')
+ self.user_site = os.path.join(self.tmpdir, 'S')
+ site.USER_BASE = self.user_base
+ site.USER_SITE = self.user_site
+ install_module.USER_BASE = self.user_base
+ install_module.USER_SITE = self.user_site
+
+ def _expanduser(path):
+ return self.tmpdir
+ self.old_expand = os.path.expanduser
+ os.path.expanduser = _expanduser
+
+ try:
+ # this is the actual test
+ self._test_user_site()
+ finally:
+ site.USER_BASE = self.old_user_base
+ site.USER_SITE = self.old_user_site
+ install_module.USER_BASE = self.old_user_base
+ install_module.USER_SITE = self.old_user_site
+ os.path.expanduser = self.old_expand
+
+ def _test_user_site(self):
+ for key in ('nt_user', 'unix_user', 'os2_home'):
+ self.assertTrue(key in INSTALL_SCHEMES)
+
+ dist = Distribution({'name': 'xx'})
+ cmd = install(dist)
+
+ # making sure the user option is there
+ options = [name for name, short, lable in
+ cmd.user_options]
+ self.assertTrue('user' in options)
+
+ # setting a value
+ cmd.user = 1
+
+ # user base and site shouldn't be created yet
+ self.assertTrue(not os.path.exists(self.user_base))
+ self.assertTrue(not os.path.exists(self.user_site))
+
+ # let's run finalize
+ cmd.ensure_finalized()
+
+ # now they should
+ self.assertTrue(os.path.exists(self.user_base))
+ self.assertTrue(os.path.exists(self.user_site))
+
+ self.assertTrue('userbase' in cmd.config_vars)
+ self.assertTrue('usersite' in cmd.config_vars)
+
+ def test_handle_extra_path(self):
+ dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
+ cmd = install(dist)
+
+ # two elements
+ cmd.handle_extra_path()
+ self.assertEqual(cmd.extra_path, ['path', 'dirs'])
+ self.assertEqual(cmd.extra_dirs, 'dirs')
+ self.assertEqual(cmd.path_file, 'path')
+
+ # one element
+ cmd.extra_path = ['path']
+ cmd.handle_extra_path()
+ self.assertEqual(cmd.extra_path, ['path'])
+ self.assertEqual(cmd.extra_dirs, 'path')
+ self.assertEqual(cmd.path_file, 'path')
+
+ # none
+ dist.extra_path = cmd.extra_path = None
+ cmd.handle_extra_path()
+ self.assertEqual(cmd.extra_path, None)
+ self.assertEqual(cmd.extra_dirs, '')
+ self.assertEqual(cmd.path_file, None)
+
+ # three elements (no way !)
+ cmd.extra_path = 'path,dirs,again'
+ self.assertRaises(DistutilsOptionError, cmd.handle_extra_path)
+
+ def test_finalize_options(self):
+ dist = Distribution({'name': 'xx'})
+ cmd = install(dist)
+
+ # must supply either prefix/exec-prefix/home or
+ # install-base/install-platbase -- not both
+ cmd.prefix = 'prefix'
+ cmd.install_base = 'base'
+ self.assertRaises(DistutilsOptionError, cmd.finalize_options)
+
+ # must supply either home or prefix/exec-prefix -- not both
+ cmd.install_base = None
+ cmd.home = 'home'
+ self.assertRaises(DistutilsOptionError, cmd.finalize_options)
+
+ # can't combine user with with prefix/exec_prefix/home or
+ # install_(plat)base
+ cmd.prefix = None
+ cmd.user = 'user'
+ self.assertRaises(DistutilsOptionError, cmd.finalize_options)
+
+ def test_record(self):
+ install_dir = self.mkdtemp()
+ project_dir, dist = self.create_dist(scripts=['hello'])
+ self.addCleanup(os.chdir, os.getcwd())
+ os.chdir(project_dir)
+ self.write_file('hello', "print('o hai')")
+
+ cmd = install(dist)
+ dist.command_obj['install'] = cmd
+ cmd.root = install_dir
+ cmd.record = os.path.join(project_dir, 'RECORD')
+ cmd.ensure_finalized()
+ cmd.run()
+
+ f = open(cmd.record)
+ try:
+ content = f.read()
+ finally:
+ f.close()
+
+ found = [os.path.basename(line) for line in content.splitlines()]
+ expected = ['hello',
+ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
+ self.assertEqual(found, expected)
+
+ def test_record_extensions(self):
+ install_dir = self.mkdtemp()
+ project_dir, dist = self.create_dist(ext_modules=[
+ Extension('xx', ['xxmodule.c'])])
+ self.addCleanup(os.chdir, os.getcwd())
+ os.chdir(project_dir)
+ support.copy_xxmodule_c(project_dir)
+
+ buildextcmd = build_ext(dist)
+ support.fixup_build_ext(buildextcmd)
+ buildextcmd.ensure_finalized()
+
+ cmd = install(dist)
+ dist.command_obj['install'] = cmd
+ dist.command_obj['build_ext'] = buildextcmd
+ cmd.root = install_dir
+ cmd.record = os.path.join(project_dir, 'RECORD')
+ cmd.ensure_finalized()
+ cmd.run()
+
+ f = open(cmd.record)
+ try:
+ content = f.read()
+ finally:
+ f.close()
+
+ found = [os.path.basename(line) for line in content.splitlines()]
+ expected = [_make_ext_name('xx'),
+ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
+ self.assertEqual(found, expected)
+
+ def test_debug_mode(self):
+ # this covers the code called when DEBUG is set
+ old_logs_len = len(self.logs)
+ install_module.DEBUG = True
+ try:
+ with captured_stdout():
+ self.test_record()
+ finally:
+ install_module.DEBUG = False
+ self.assertTrue(len(self.logs) > old_logs_len)
def test_suite():
return unittest.makeSuite(InstallTestCase)
diff --git a/Lib/distutils/tests/test_register.py b/Lib/distutils/tests/test_register.py
index dd60f8c..aa9bc43 100644
--- a/Lib/distutils/tests/test_register.py
+++ b/Lib/distutils/tests/test_register.py
@@ -1,5 +1,5 @@
-"""Tests for distutils.command.register."""
# -*- encoding: utf8 -*-
+"""Tests for distutils.command.register."""
import sys
import os
import unittest
@@ -138,7 +138,7 @@
# let's see what the server received : we should
# have 2 similar requests
- self.assertTrue(self.conn.reqs, 2)
+ self.assertEqual(len(self.conn.reqs), 2)
req1 = dict(self.conn.reqs[0].headers)
req2 = dict(self.conn.reqs[1].headers)
self.assertEqual(req2['Content-length'], req1['Content-length'])
@@ -168,7 +168,7 @@
del register_module.raw_input
# we should have send a request
- self.assertTrue(self.conn.reqs, 1)
+ self.assertEqual(len(self.conn.reqs), 1)
req = self.conn.reqs[0]
headers = dict(req.headers)
self.assertEqual(headers['Content-length'], '608')
@@ -186,7 +186,7 @@
del register_module.raw_input
# we should have send a request
- self.assertTrue(self.conn.reqs, 1)
+ self.assertEqual(len(self.conn.reqs), 1)
req = self.conn.reqs[0]
headers = dict(req.headers)
self.assertEqual(headers['Content-length'], '290')
@@ -246,6 +246,24 @@
finally:
del register_module.raw_input
+ # and finally a Unicode test (bug #12114)
+ metadata = {'url': u'xxx', 'author': u'\u00c9ric',
+ 'author_email': u'xxx', u'name': 'xxx',
+ 'version': u'xxx',
+ 'description': u'Something about esszet \u00df',
+ 'long_description': u'More things about esszet \u00df'}
+
+ cmd = self._get_cmd(metadata)
+ cmd.ensure_finalized()
+ cmd.strict = 1
+ inputs = RawInputs('1', 'tarek', 'y')
+ register_module.raw_input = inputs.__call__
+ # let's run the command
+ try:
+ cmd.run()
+ finally:
+ del register_module.raw_input
+
def test_check_metadata_deprecated(self):
# makes sure make_metadata is deprecated
cmd = self._get_cmd()
diff --git a/Lib/distutils/tests/test_sdist.py b/Lib/distutils/tests/test_sdist.py
index 54a32b8..33f6ee6 100644
--- a/Lib/distutils/tests/test_sdist.py
+++ b/Lib/distutils/tests/test_sdist.py
@@ -1,9 +1,11 @@
"""Tests for distutils.command.sdist."""
import os
-import unittest
-import shutil
-import zipfile
import tarfile
+import unittest
+import warnings
+import zipfile
+from os.path import join
+from textwrap import dedent
# zlib is not used here, but if it's not available
# the tests that use zipfile may fail
@@ -19,20 +21,15 @@
except ImportError:
UID_GID_SUPPORT = False
-from os.path import join
-import sys
-import tempfile
-import warnings
-
from test.test_support import captured_stdout, check_warnings, run_unittest
from distutils.command.sdist import sdist, show_formats
from distutils.core import Distribution
from distutils.tests.test_config import PyPIRCCommandTestCase
-from distutils.errors import DistutilsExecError, DistutilsOptionError
+from distutils.errors import DistutilsOptionError
from distutils.spawn import find_executable
-from distutils.tests import support
from distutils.log import WARN
+from distutils.filelist import FileList
from distutils.archive_util import ARCHIVE_FORMATS
SETUP_PY = """
@@ -89,9 +86,6 @@
dist.include_package_data = True
cmd = sdist(dist)
cmd.dist_dir = 'dist'
- def _warn(*args):
- pass
- cmd.warn = _warn
return dist, cmd
@unittest.skipUnless(zlib, "requires zlib")
@@ -246,7 +240,8 @@
# with the `check` subcommand
cmd.ensure_finalized()
cmd.run()
- warnings = self.get_logs(WARN)
+ warnings = [msg for msg in self.get_logs(WARN) if
+ msg.startswith('warning: check:')]
self.assertEqual(len(warnings), 2)
# trying with a complete set of metadata
@@ -255,7 +250,8 @@
cmd.ensure_finalized()
cmd.metadata_check = 0
cmd.run()
- warnings = self.get_logs(WARN)
+ warnings = [msg for msg in self.get_logs(WARN) if
+ msg.startswith('warning: check:')]
self.assertEqual(len(warnings), 0)
def test_check_metadata_deprecated(self):
@@ -277,7 +273,6 @@
self.assertEqual(len(output), num_formats)
def test_finalize_options(self):
-
dist, cmd = self.get_cmd()
cmd.finalize_options()
@@ -347,6 +342,32 @@
finally:
archive.close()
+ # the following tests make sure there is a nice error message instead
+ # of a traceback when parsing an invalid manifest template
+
+ def _test_template(self, content):
+ dist, cmd = self.get_cmd()
+ os.chdir(self.tmp_dir)
+ self.write_file('MANIFEST.in', content)
+ cmd.ensure_finalized()
+ cmd.filelist = FileList()
+ cmd.read_template()
+ warnings = self.get_logs(WARN)
+ self.assertEqual(len(warnings), 1)
+
+ def test_invalid_template_unknown_command(self):
+ self._test_template('taunt knights *')
+
+ def test_invalid_template_wrong_arguments(self):
+ # this manifest command takes one argument
+ self._test_template('prune')
+
+ @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only')
+ def test_invalid_template_wrong_path(self):
+ # on Windows, trailing slashes are not allowed
+ # this used to crash instead of raising a warning: #8286
+ self._test_template('include examples/')
+
@unittest.skipUnless(zlib, "requires zlib")
def test_get_file_list(self):
# make sure MANIFEST is recalculated
@@ -355,6 +376,7 @@
# filling data_files by pointing files in package_data
dist.package_data = {'somecode': ['*.txt']}
self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
+ cmd.formats = ['gztar']
cmd.ensure_finalized()
cmd.run()
@@ -388,6 +410,7 @@
self.assertEqual(len(manifest2), 6)
self.assertIn('doc2.txt', manifest2[-1])
+ @unittest.skipUnless(zlib, "requires zlib")
def test_manifest_marker(self):
# check that autogenerated MANIFESTs have a marker
dist, cmd = self.get_cmd()
@@ -404,12 +427,34 @@
self.assertEqual(manifest[0],
'# file GENERATED by distutils, do NOT edit')
+ @unittest.skipUnless(zlib, 'requires zlib')
+ def test_manifest_comments(self):
+ # make sure comments don't cause exceptions or wrong includes
+ contents = dedent("""\
+ # bad.py
+ #bad.py
+ good.py
+ """)
+ dist, cmd = self.get_cmd()
+ cmd.ensure_finalized()
+ self.write_file((self.tmp_dir, cmd.manifest), contents)
+ self.write_file((self.tmp_dir, 'good.py'), '# pick me!')
+ self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!")
+ self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!")
+ cmd.run()
+ self.assertEqual(cmd.filelist.files, ['good.py'])
+
+ @unittest.skipUnless(zlib, "requires zlib")
def test_manual_manifest(self):
# check that a MANIFEST without a marker is left alone
dist, cmd = self.get_cmd()
+ cmd.formats = ['gztar']
cmd.ensure_finalized()
self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
+ self.write_file((self.tmp_dir, 'README.manual'),
+ 'This project maintains its MANIFEST file itself.')
cmd.run()
+ self.assertEqual(cmd.filelist.files, ['README.manual'])
f = open(cmd.manifest)
try:
@@ -420,6 +465,15 @@
self.assertEqual(manifest, ['README.manual'])
+ archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
+ archive = tarfile.open(archive_name)
+ try:
+ filenames = [tarinfo.name for tarinfo in archive]
+ finally:
+ archive.close()
+ self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO',
+ 'fake-1.0/README.manual'])
+
def test_suite():
return unittest.makeSuite(SDistTestCase)
diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py
index f06e4fd..6c49f0b 100644
--- a/Lib/distutils/util.py
+++ b/Lib/distutils/util.py
@@ -97,9 +97,7 @@
from distutils.sysconfig import get_config_vars
cfgvars = get_config_vars()
- macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
- if not macver:
- macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
+ macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
if 1:
# Always calculate the release of the running machine,
diff --git a/Lib/filecmp.py b/Lib/filecmp.py
index 89a4835..4728317 100644
--- a/Lib/filecmp.py
+++ b/Lib/filecmp.py
@@ -48,11 +48,12 @@
if s1[1] != s2[1]:
return False
- result = _cache.get((f1, f2))
- if result and (s1, s2) == result[:2]:
- return result[2]
- outcome = _do_cmp(f1, f2)
- _cache[f1, f2] = s1, s2, outcome
+ outcome = _cache.get((f1, f2, s1, s2))
+ if outcome is None:
+ outcome = _do_cmp(f1, f2)
+ if len(_cache) > 100: # limit the maximum size of the cache
+ _cache.clear()
+ _cache[f1, f2, s1, s2] = outcome
return outcome
def _sig(st):
diff --git a/Lib/ftplib.py b/Lib/ftplib.py
index 72d31a1..c896433 100644
--- a/Lib/ftplib.py
+++ b/Lib/ftplib.py
@@ -325,32 +325,39 @@
if self.passiveserver:
host, port = self.makepasv()
conn = socket.create_connection((host, port), self.timeout)
- if rest is not None:
- self.sendcmd("REST %s" % rest)
- resp = self.sendcmd(cmd)
- # Some servers apparently send a 200 reply to
- # a LIST or STOR command, before the 150 reply
- # (and way before the 226 reply). This seems to
- # be in violation of the protocol (which only allows
- # 1xx or error messages for LIST), so we just discard
- # this response.
- if resp[0] == '2':
- resp = self.getresp()
- if resp[0] != '1':
- raise error_reply, resp
+ try:
+ if rest is not None:
+ self.sendcmd("REST %s" % rest)
+ resp = self.sendcmd(cmd)
+ # Some servers apparently send a 200 reply to
+ # a LIST or STOR command, before the 150 reply
+ # (and way before the 226 reply). This seems to
+ # be in violation of the protocol (which only allows
+ # 1xx or error messages for LIST), so we just discard
+ # this response.
+ if resp[0] == '2':
+ resp = self.getresp()
+ if resp[0] != '1':
+ raise error_reply, resp
+ except:
+ conn.close()
+ raise
else:
sock = self.makeport()
- if rest is not None:
- self.sendcmd("REST %s" % rest)
- resp = self.sendcmd(cmd)
- # See above.
- if resp[0] == '2':
- resp = self.getresp()
- if resp[0] != '1':
- raise error_reply, resp
- conn, sockaddr = sock.accept()
- if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
- conn.settimeout(self.timeout)
+ try:
+ if rest is not None:
+ self.sendcmd("REST %s" % rest)
+ resp = self.sendcmd(cmd)
+ # See above.
+ if resp[0] == '2':
+ resp = self.getresp()
+ if resp[0] != '1':
+ raise error_reply, resp
+ conn, sockaddr = sock.accept()
+ if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
+ conn.settimeout(self.timeout)
+ finally:
+ sock.close()
if resp[:3] == '150':
# this is conditional in case we received a 125
size = parse150(resp)
@@ -575,11 +582,11 @@
def close(self):
'''Close the connection without assuming anything about it.'''
- if self.file:
+ if self.file is not None:
self.file.close()
+ if self.sock is not None:
self.sock.close()
- self.file = self.sock = None
-
+ self.file = self.sock = None
try:
import ssl
diff --git a/Lib/hashlib.py b/Lib/hashlib.py
index 48f2cfd..2732d18 100644
--- a/Lib/hashlib.py
+++ b/Lib/hashlib.py
@@ -64,26 +64,29 @@
def __get_builtin_constructor(name):
- if name in ('SHA1', 'sha1'):
- import _sha
- return _sha.new
- elif name in ('MD5', 'md5'):
- import _md5
- return _md5.new
- elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
- import _sha256
- bs = name[3:]
- if bs == '256':
- return _sha256.sha256
- elif bs == '224':
- return _sha256.sha224
- elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
- import _sha512
- bs = name[3:]
- if bs == '512':
- return _sha512.sha512
- elif bs == '384':
- return _sha512.sha384
+ try:
+ if name in ('SHA1', 'sha1'):
+ import _sha
+ return _sha.new
+ elif name in ('MD5', 'md5'):
+ import _md5
+ return _md5.new
+ elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
+ import _sha256
+ bs = name[3:]
+ if bs == '256':
+ return _sha256.sha256
+ elif bs == '224':
+ return _sha256.sha224
+ elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
+ import _sha512
+ bs = name[3:]
+ if bs == '512':
+ return _sha512.sha512
+ elif bs == '384':
+ return _sha512.sha384
+ except ImportError:
+ pass # no extension module, this hash is unsupported.
raise ValueError('unsupported hash type %s' % name)
diff --git a/Lib/heapq.py b/Lib/heapq.py
index 74f7310..fcaca13 100644
--- a/Lib/heapq.py
+++ b/Lib/heapq.py
@@ -178,7 +178,7 @@
return item
def heapify(x):
- """Transform list into a heap, in-place, in O(len(heap)) time."""
+ """Transform list into a heap, in-place, in O(len(x)) time."""
n = len(x)
# Transform bottom-up. The largest index there's any point to looking at
# is the largest with a child index in-range, so must have 2*i + 1 < n,
@@ -368,7 +368,7 @@
return [min(chain(head, it))]
return [min(chain(head, it), key=key)]
- # When n>=size, it's faster to use sort()
+ # When n>=size, it's faster to use sorted()
try:
size = len(iterable)
except (TypeError, AttributeError):
@@ -406,7 +406,7 @@
return [max(chain(head, it))]
return [max(chain(head, it), key=key)]
- # When n>=size, it's faster to use sort()
+ # When n>=size, it's faster to use sorted()
try:
size = len(iterable)
except (TypeError, AttributeError):
diff --git a/Lib/httplib.py b/Lib/httplib.py
index 6e72e2c..9853285 100644
--- a/Lib/httplib.py
+++ b/Lib/httplib.py
@@ -939,10 +939,10 @@
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional
- message_body argument can be used to pass message body
+ message_body argument can be used to pass a message body
associated with the request. The message body will be sent in
- the same packet as the message headers if possible. The
- message_body should be a string.
+ the same packet as the message headers if it is string, otherwise it is
+ sent as a separate packet.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
@@ -1322,71 +1322,3 @@
return L + self._file.readlines()
else:
return L + self._file.readlines(size)
-
-def test():
- """Test this module.
-
- A hodge podge of tests collected here, because they have too many
- external dependencies for the regular test suite.
- """
-
- import sys
- import getopt
- opts, args = getopt.getopt(sys.argv[1:], 'd')
- dl = 0
- for o, a in opts:
- if o == '-d': dl = dl + 1
- host = 'www.python.org'
- selector = '/'
- if args[0:]: host = args[0]
- if args[1:]: selector = args[1]
- h = HTTP()
- h.set_debuglevel(dl)
- h.connect(host)
- h.putrequest('GET', selector)
- h.endheaders()
- status, reason, headers = h.getreply()
- print 'status =', status
- print 'reason =', reason
- print "read", len(h.getfile().read())
- print
- if headers:
- for header in headers.headers: print header.strip()
- print
-
- # minimal test that code to extract host from url works
- class HTTP11(HTTP):
- _http_vsn = 11
- _http_vsn_str = 'HTTP/1.1'
-
- h = HTTP11('www.python.org')
- h.putrequest('GET', 'http://www.python.org/~jeremy/')
- h.endheaders()
- h.getreply()
- h.close()
-
- try:
- import ssl
- except ImportError:
- pass
- else:
-
- for host, selector in (('sourceforge.net', '/projects/python'),
- ):
- print "https://%s%s" % (host, selector)
- hs = HTTPS()
- hs.set_debuglevel(dl)
- hs.connect(host)
- hs.putrequest('GET', selector)
- hs.endheaders()
- status, reason, headers = hs.getreply()
- print 'status =', status
- print 'reason =', reason
- print "read", len(hs.getfile().read())
- print
- if headers:
- for header in headers.headers: print header.strip()
- print
-
-if __name__ == '__main__':
- test()
diff --git a/Lib/idlelib/IOBinding.py b/Lib/idlelib/IOBinding.py
index a5b610e..c515432 100644
--- a/Lib/idlelib/IOBinding.py
+++ b/Lib/idlelib/IOBinding.py
@@ -266,7 +266,7 @@
self.reset_undo()
self.set_filename(filename)
self.text.mark_set("insert", "1.0")
- self.text.see("insert")
+ self.text.yview("insert")
self.updaterecentfileslist(filename)
return True
@@ -320,17 +320,20 @@
return "yes"
message = "Do you want to save %s before closing?" % (
self.filename or "this untitled document")
- m = tkMessageBox.Message(
- title="Save On Close",
- message=message,
- icon=tkMessageBox.QUESTION,
- type=tkMessageBox.YESNOCANCEL,
- master=self.text)
- reply = m.show()
- if reply == "yes":
+ confirm = tkMessageBox.askyesnocancel(
+ title="Save On Close",
+ message=message,
+ default=tkMessageBox.YES,
+ master=self.text)
+ if confirm:
+ reply = "yes"
self.save(None)
if not self.get_saved():
reply = "cancel"
+ elif confirm is None:
+ reply = "cancel"
+ else:
+ reply = "no"
self.text.focus_set()
return reply
@@ -339,7 +342,7 @@
self.save_as(event)
else:
if self.writefile(self.filename):
- self.set_saved(1)
+ self.set_saved(True)
try:
self.editwin.store_file_breaks()
except AttributeError: # may be a PyShell
@@ -465,15 +468,12 @@
self.text.insert("end-1c", "\n")
def print_window(self, event):
- m = tkMessageBox.Message(
- title="Print",
- message="Print to Default Printer",
- icon=tkMessageBox.QUESTION,
- type=tkMessageBox.OKCANCEL,
- default=tkMessageBox.OK,
- master=self.text)
- reply = m.show()
- if reply != tkMessageBox.OK:
+ confirm = tkMessageBox.askokcancel(
+ title="Print",
+ message="Print to Default Printer",
+ default=tkMessageBox.OK,
+ master=self.text)
+ if not confirm:
self.text.focus_set()
return "break"
tempfilename = None
@@ -488,8 +488,8 @@
if not self.writefile(tempfilename):
os.unlink(tempfilename)
return "break"
- platform=os.name
- printPlatform=1
+ platform = os.name
+ printPlatform = True
if platform == 'posix': #posix platform
command = idleConf.GetOption('main','General',
'print-command-posix')
@@ -497,7 +497,7 @@
elif platform == 'nt': #win32 platform
command = idleConf.GetOption('main','General','print-command-win')
else: #no printing for this platform
- printPlatform=0
+ printPlatform = False
if printPlatform: #we can try to print for this platform
command = command % filename
pipe = os.popen(command, "r")
@@ -511,7 +511,7 @@
output = "Printing command: %s\n" % repr(command) + output
tkMessageBox.showerror("Print status", output, master=self.text)
else: #no printing for this platform
- message="Printing is not enabled for this platform: %s" % platform
+ message = "Printing is not enabled for this platform: %s" % platform
tkMessageBox.showinfo("Print status", message, master=self.text)
if tempfilename:
os.unlink(tempfilename)
diff --git a/Lib/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt
index 5eac219..46ef3cb 100644
--- a/Lib/idlelib/NEWS.txt
+++ b/Lib/idlelib/NEWS.txt
@@ -1,10 +1,15 @@
What's New in IDLE 2.7.2?
=======================
-*Release date: XX-XX-XXXX*
+*Release date: 29-May-2011*
+
+- Issue #6378: Further adjust idle.bat to start associated Python
+
+- Issue #11896: Save on Close failed despite selecting "Yes" in dialog.
- <Home> toggle failing on Tk 8.5, causing IDLE exits and strange selection
behavior. Issue 4676. Improve selection extension behaviour.
+
- <Home> toggle non-functional when NumLock set on Windows. Issue 3851.
@@ -31,7 +36,7 @@
- Tk 8.5 Text widget requires 'wordprocessor' tabstyle attr to handle
mixed space/tab properly. Issue 5129, patch by Guilherme Polo.
-
+
- Issue #3549: On MacOS the preferences menu was not present
diff --git a/Lib/idlelib/PyShell.py b/Lib/idlelib/PyShell.py
index 0c95df4..9dd43cf 100644
--- a/Lib/idlelib/PyShell.py
+++ b/Lib/idlelib/PyShell.py
@@ -61,7 +61,7 @@
file = warning_stream
try:
file.write(warnings.formatwarning(message, category, filename,
- lineno, file=file, line=line))
+ lineno, line=line))
except IOError:
pass ## file (probably __stderr__) is invalid, warning dropped.
warnings.showwarning = idle_showwarning
diff --git a/Lib/idlelib/ScriptBinding.py b/Lib/idlelib/ScriptBinding.py
index 3a44165..1139b30 100644
--- a/Lib/idlelib/ScriptBinding.py
+++ b/Lib/idlelib/ScriptBinding.py
@@ -26,6 +26,7 @@
from idlelib import PyShell
from idlelib.configHandler import idleConf
+from idlelib import macosxSupport
IDENTCHARS = string.ascii_letters + string.digits + "_"
@@ -53,6 +54,9 @@
self.flist = self.editwin.flist
self.root = self.editwin.root
+ if macosxSupport.runningAsOSXApp():
+ self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
+
def check_module_event(self, event):
filename = self.getfilename()
if not filename:
@@ -166,6 +170,19 @@
interp.runcode(code)
return 'break'
+ if macosxSupport.runningAsOSXApp():
+ # Tk-Cocoa in MacOSX is broken until at least
+ # Tk 8.5.9, and without this rather
+ # crude workaround IDLE would hang when a user
+ # tries to run a module using the keyboard shortcut
+ # (the menu item works fine).
+ _run_module_event = run_module_event
+
+ def run_module_event(self, event):
+ self.editwin.text_frame.after(200,
+ lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
+ return 'break'
+
def getfilename(self):
"""Get source filename. If not saved, offer to save (or create) file
@@ -184,9 +201,9 @@
if autosave and filename:
self.editwin.io.save(None)
else:
- reply = self.ask_save_dialog()
+ confirm = self.ask_save_dialog()
self.editwin.text.focus_set()
- if reply == "ok":
+ if confirm:
self.editwin.io.save(None)
filename = self.editwin.io.filename
else:
@@ -195,13 +212,11 @@
def ask_save_dialog(self):
msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
- mb = tkMessageBox.Message(title="Save Before Run or Check",
- message=msg,
- icon=tkMessageBox.QUESTION,
- type=tkMessageBox.OKCANCEL,
- default=tkMessageBox.OK,
- master=self.editwin.text)
- return mb.show()
+ confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
+ message=msg,
+ default=tkMessageBox.OK,
+ master=self.editwin.text)
+ return confirm
def errorbox(self, title, message):
# XXX This should really be a function of EditorWindow...
diff --git a/Lib/idlelib/idle.bat b/Lib/idlelib/idle.bat
index cc653dc..e77b96e 100755
--- a/Lib/idlelib/idle.bat
+++ b/Lib/idlelib/idle.bat
@@ -1,4 +1,4 @@
@echo off
rem Start IDLE using the appropriate Python interpreter
set CURRDIR=%~dp0
-start "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9
+start "IDLE" "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9
diff --git a/Lib/idlelib/idlever.py b/Lib/idlelib/idlever.py
index b6e1a1d..3f8bcff 100644
--- a/Lib/idlelib/idlever.py
+++ b/Lib/idlelib/idlever.py
@@ -1 +1 @@
-IDLE_VERSION = "2.7.1"
+IDLE_VERSION = "2.7.2"
diff --git a/Lib/imaplib.py b/Lib/imaplib.py
index 5693191..c576927 100644
--- a/Lib/imaplib.py
+++ b/Lib/imaplib.py
@@ -1158,28 +1158,17 @@
self.port = port
self.sock = socket.create_connection((host, port))
self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
+ self.file = self.sslobj.makefile('rb')
def read(self, size):
"""Read 'size' bytes from remote."""
- # sslobj.read() sometimes returns < size bytes
- chunks = []
- read = 0
- while read < size:
- data = self.sslobj.read(min(size-read, 16384))
- read += len(data)
- chunks.append(data)
-
- return ''.join(chunks)
+ return self.file.read(size)
def readline(self):
"""Read line from remote."""
- line = []
- while 1:
- char = self.sslobj.read(1)
- line.append(char)
- if char in ("\n", ""): return ''.join(line)
+ return self.file.readline()
def send(self, data):
@@ -1195,6 +1184,7 @@
def shutdown(self):
"""Close I/O established in "open"."""
+ self.file.close()
self.sock.close()
diff --git a/Lib/inspect.py b/Lib/inspect.py
index b0b2d3a..c727530 100644
--- a/Lib/inspect.py
+++ b/Lib/inspect.py
@@ -524,9 +524,13 @@
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An IOError
is raised if the source code cannot be retrieved."""
- file = getsourcefile(object)
- if not file:
+
+ file = getfile(object)
+ sourcefile = getsourcefile(object)
+ if not sourcefile and file[0] + file[-1] != '<>':
raise IOError('source code not available')
+ file = sourcefile if sourcefile else file
+
module = getmodule(object, file)
if module:
lines = linecache.getlines(file, module.__dict__)
diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py
index eeebf45..1f2da72 100644
--- a/Lib/json/decoder.py
+++ b/Lib/json/decoder.py
@@ -4,7 +4,7 @@
import sys
import struct
-from json.scanner import make_scanner
+from json import scanner
try:
from _json import scanstring as c_scanstring
except ImportError:
@@ -356,7 +356,7 @@
self.parse_object = JSONObject
self.parse_array = JSONArray
self.parse_string = scanstring
- self.scan_once = make_scanner(self)
+ self.scan_once = scanner.make_scanner(self)
def decode(self, s, _w=WHITESPACE.match):
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
diff --git a/Lib/json/tests/__init__.py b/Lib/json/tests/__init__.py
index 1a1e3e6..90cb2b7 100644
--- a/Lib/json/tests/__init__.py
+++ b/Lib/json/tests/__init__.py
@@ -1,7 +1,46 @@
import os
import sys
-import unittest
+import json
import doctest
+import unittest
+
+from test import test_support
+
+# import json with and without accelerations
+cjson = test_support.import_fresh_module('json', fresh=['_json'])
+pyjson = test_support.import_fresh_module('json', blocked=['_json'])
+
+# create two base classes that will be used by the other tests
+class PyTest(unittest.TestCase):
+ json = pyjson
+ loads = staticmethod(pyjson.loads)
+ dumps = staticmethod(pyjson.dumps)
+
+@unittest.skipUnless(cjson, 'requires _json')
+class CTest(unittest.TestCase):
+ if cjson is not None:
+ json = cjson
+ loads = staticmethod(cjson.loads)
+ dumps = staticmethod(cjson.dumps)
+
+# test PyTest and CTest checking if the functions come from the right module
+class TestPyTest(PyTest):
+ def test_pyjson(self):
+ self.assertEqual(self.json.scanner.make_scanner.__module__,
+ 'json.scanner')
+ self.assertEqual(self.json.decoder.scanstring.__module__,
+ 'json.decoder')
+ self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
+ 'json.encoder')
+
+class TestCTest(CTest):
+ def test_cjson(self):
+ self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
+ self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
+ self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
+ self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
+ '_json')
+
here = os.path.dirname(__file__)
@@ -17,12 +56,11 @@
return suite
def additional_tests():
- import json
- import json.encoder
- import json.decoder
suite = unittest.TestSuite()
for mod in (json, json.encoder, json.decoder):
suite.addTest(doctest.DocTestSuite(mod))
+ suite.addTest(TestPyTest('test_pyjson'))
+ suite.addTest(TestCTest('test_cjson'))
return suite
def main():
diff --git a/Lib/json/tests/test_check_circular.py b/Lib/json/tests/test_check_circular.py
index 3c3f96a..3ad3d24 100644
--- a/Lib/json/tests/test_check_circular.py
+++ b/Lib/json/tests/test_check_circular.py
@@ -1,30 +1,34 @@
-from unittest import TestCase
-import json
+from json.tests import PyTest, CTest
+
def default_iterable(obj):
return list(obj)
-class TestCheckCircular(TestCase):
+class TestCheckCircular(object):
def test_circular_dict(self):
dct = {}
dct['a'] = dct
- self.assertRaises(ValueError, json.dumps, dct)
+ self.assertRaises(ValueError, self.dumps, dct)
def test_circular_list(self):
lst = []
lst.append(lst)
- self.assertRaises(ValueError, json.dumps, lst)
+ self.assertRaises(ValueError, self.dumps, lst)
def test_circular_composite(self):
dct2 = {}
dct2['a'] = []
dct2['a'].append(dct2)
- self.assertRaises(ValueError, json.dumps, dct2)
+ self.assertRaises(ValueError, self.dumps, dct2)
def test_circular_default(self):
- json.dumps([set()], default=default_iterable)
- self.assertRaises(TypeError, json.dumps, [set()])
+ self.dumps([set()], default=default_iterable)
+ self.assertRaises(TypeError, self.dumps, [set()])
def test_circular_off_default(self):
- json.dumps([set()], default=default_iterable, check_circular=False)
- self.assertRaises(TypeError, json.dumps, [set()], check_circular=False)
+ self.dumps([set()], default=default_iterable, check_circular=False)
+ self.assertRaises(TypeError, self.dumps, [set()], check_circular=False)
+
+
+class TestPyCheckCircular(TestCheckCircular, PyTest): pass
+class TestCCheckCircular(TestCheckCircular, CTest): pass
diff --git a/Lib/json/tests/test_decode.py b/Lib/json/tests/test_decode.py
index 95088b4..aa8bbe9 100644
--- a/Lib/json/tests/test_decode.py
+++ b/Lib/json/tests/test_decode.py
@@ -1,18 +1,17 @@
import decimal
-from unittest import TestCase
from StringIO import StringIO
-
-import json
from collections import OrderedDict
+from json.tests import PyTest, CTest
-class TestDecode(TestCase):
+
+class TestDecode(object):
def test_decimal(self):
- rval = json.loads('1.1', parse_float=decimal.Decimal)
+ rval = self.loads('1.1', parse_float=decimal.Decimal)
self.assertTrue(isinstance(rval, decimal.Decimal))
self.assertEqual(rval, decimal.Decimal('1.1'))
def test_float(self):
- rval = json.loads('1', parse_int=float)
+ rval = self.loads('1', parse_int=float)
self.assertTrue(isinstance(rval, float))
self.assertEqual(rval, 1.0)
@@ -20,27 +19,32 @@
# Several optimizations were made that skip over calls to
# the whitespace regex, so this test is designed to try and
# exercise the uncommon cases. The array cases are already covered.
- rval = json.loads('{ "key" : "value" , "k":"v" }')
+ rval = self.loads('{ "key" : "value" , "k":"v" }')
self.assertEqual(rval, {"key":"value", "k":"v"})
def test_empty_objects(self):
- self.assertEqual(json.loads('{}'), {})
- self.assertEqual(json.loads('[]'), [])
- self.assertEqual(json.loads('""'), "")
+ self.assertEqual(self.loads('{}'), {})
+ self.assertEqual(self.loads('[]'), [])
+ self.assertEqual(self.loads('""'), u"")
+ self.assertIsInstance(self.loads('""'), unicode)
def test_object_pairs_hook(self):
s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
("qrt", 5), ("pad", 6), ("hoy", 7)]
- self.assertEqual(json.loads(s), eval(s))
- self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
- self.assertEqual(json.load(StringIO(s),
- object_pairs_hook=lambda x: x), p)
- od = json.loads(s, object_pairs_hook=OrderedDict)
+ self.assertEqual(self.loads(s), eval(s))
+ self.assertEqual(self.loads(s, object_pairs_hook=lambda x: x), p)
+ self.assertEqual(self.json.load(StringIO(s),
+ object_pairs_hook=lambda x: x), p)
+ od = self.loads(s, object_pairs_hook=OrderedDict)
self.assertEqual(od, OrderedDict(p))
self.assertEqual(type(od), OrderedDict)
# the object_pairs_hook takes priority over the object_hook
- self.assertEqual(json.loads(s,
+ self.assertEqual(self.loads(s,
object_pairs_hook=OrderedDict,
object_hook=lambda x: None),
OrderedDict(p))
+
+
+class TestPyDecode(TestDecode, PyTest): pass
+class TestCDecode(TestDecode, CTest): pass
diff --git a/Lib/json/tests/test_default.py b/Lib/json/tests/test_default.py
index 6a03eeb..c2a07f6 100644
--- a/Lib/json/tests/test_default.py
+++ b/Lib/json/tests/test_default.py
@@ -1,9 +1,12 @@
-from unittest import TestCase
+from json.tests import PyTest, CTest
-import json
-class TestDefault(TestCase):
+class TestDefault(object):
def test_default(self):
self.assertEqual(
- json.dumps(type, default=repr),
- json.dumps(repr(type)))
+ self.dumps(type, default=repr),
+ self.dumps(repr(type)))
+
+
+class TestPyDefault(TestDefault, PyTest): pass
+class TestCDefault(TestDefault, CTest): pass
diff --git a/Lib/json/tests/test_dump.py b/Lib/json/tests/test_dump.py
index 89978e0..9a7c8cc 100644
--- a/Lib/json/tests/test_dump.py
+++ b/Lib/json/tests/test_dump.py
@@ -1,21 +1,23 @@
-from unittest import TestCase
from cStringIO import StringIO
+from json.tests import PyTest, CTest
-import json
-class TestDump(TestCase):
+class TestDump(object):
def test_dump(self):
sio = StringIO()
- json.dump({}, sio)
+ self.json.dump({}, sio)
self.assertEqual(sio.getvalue(), '{}')
def test_dumps(self):
- self.assertEqual(json.dumps({}), '{}')
+ self.assertEqual(self.dumps({}), '{}')
def test_encode_truefalse(self):
- self.assertEqual(json.dumps(
+ self.assertEqual(self.dumps(
{True: False, False: True}, sort_keys=True),
'{"false": true, "true": false}')
- self.assertEqual(json.dumps(
+ self.assertEqual(self.dumps(
{2: 3.0, 4.0: 5L, False: 1, 6L: True}, sort_keys=True),
'{"false": 1, "2": 3.0, "4.0": 5, "6": true}')
+
+class TestPyDump(TestDump, PyTest): pass
+class TestCDump(TestDump, CTest): pass
diff --git a/Lib/json/tests/test_encode_basestring_ascii.py b/Lib/json/tests/test_encode_basestring_ascii.py
index 0e50110..9f9d5a5 100644
--- a/Lib/json/tests/test_encode_basestring_ascii.py
+++ b/Lib/json/tests/test_encode_basestring_ascii.py
@@ -1,8 +1,6 @@
-from unittest import TestCase
-
-import json.encoder
-from json import dumps
from collections import OrderedDict
+from json.tests import PyTest, CTest
+
CASES = [
(u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'),
@@ -23,19 +21,11 @@
(u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'),
]
-class TestEncodeBaseStringAscii(TestCase):
- def test_py_encode_basestring_ascii(self):
- self._test_encode_basestring_ascii(json.encoder.py_encode_basestring_ascii)
-
- def test_c_encode_basestring_ascii(self):
- if not json.encoder.c_encode_basestring_ascii:
- return
- self._test_encode_basestring_ascii(json.encoder.c_encode_basestring_ascii)
-
- def _test_encode_basestring_ascii(self, encode_basestring_ascii):
- fname = encode_basestring_ascii.__name__
+class TestEncodeBasestringAscii(object):
+ def test_encode_basestring_ascii(self):
+ fname = self.json.encoder.encode_basestring_ascii.__name__
for input_string, expect in CASES:
- result = encode_basestring_ascii(input_string)
+ result = self.json.encoder.encode_basestring_ascii(input_string)
self.assertEqual(result, expect,
'{0!r} != {1!r} for {2}({3!r})'.format(
result, expect, fname, input_string))
@@ -43,5 +33,9 @@
def test_ordered_dict(self):
# See issue 6105
items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
- s = json.dumps(OrderedDict(items))
+ s = self.dumps(OrderedDict(items))
self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}')
+
+
+class TestPyEncodeBasestringAscii(TestEncodeBasestringAscii, PyTest): pass
+class TestCEncodeBasestringAscii(TestEncodeBasestringAscii, CTest): pass
diff --git a/Lib/json/tests/test_fail.py b/Lib/json/tests/test_fail.py
index dd9ec41..ae962c8 100644
--- a/Lib/json/tests/test_fail.py
+++ b/Lib/json/tests/test_fail.py
@@ -1,6 +1,4 @@
-from unittest import TestCase
-
-import json
+from json.tests import PyTest, CTest
# Fri Dec 30 18:57:26 2005
JSONDOCS = [
@@ -61,15 +59,15 @@
18: "spec doesn't specify any nesting limitations",
}
-class TestFail(TestCase):
+class TestFail(object):
def test_failures(self):
for idx, doc in enumerate(JSONDOCS):
idx = idx + 1
if idx in SKIPS:
- json.loads(doc)
+ self.loads(doc)
continue
try:
- json.loads(doc)
+ self.loads(doc)
except ValueError:
pass
else:
@@ -79,7 +77,11 @@
data = {'a' : 1, (1, 2) : 2}
#This is for c encoder
- self.assertRaises(TypeError, json.dumps, data)
+ self.assertRaises(TypeError, self.dumps, data)
#This is for python encoder
- self.assertRaises(TypeError, json.dumps, data, indent=True)
+ self.assertRaises(TypeError, self.dumps, data, indent=True)
+
+
+class TestPyFail(TestFail, PyTest): pass
+class TestCFail(TestFail, CTest): pass
diff --git a/Lib/json/tests/test_float.py b/Lib/json/tests/test_float.py
index ec0cad1..12d3507 100644
--- a/Lib/json/tests/test_float.py
+++ b/Lib/json/tests/test_float.py
@@ -1,19 +1,22 @@
import math
-from unittest import TestCase
+from json.tests import PyTest, CTest
-import json
-class TestFloat(TestCase):
+class TestFloat(object):
def test_floats(self):
for num in [1617161771.7650001, math.pi, math.pi**100,
math.pi**-100, 3.1]:
- self.assertEqual(float(json.dumps(num)), num)
- self.assertEqual(json.loads(json.dumps(num)), num)
- self.assertEqual(json.loads(unicode(json.dumps(num))), num)
+ self.assertEqual(float(self.dumps(num)), num)
+ self.assertEqual(self.loads(self.dumps(num)), num)
+ self.assertEqual(self.loads(unicode(self.dumps(num))), num)
def test_ints(self):
for num in [1, 1L, 1<<32, 1<<64]:
- self.assertEqual(json.dumps(num), str(num))
- self.assertEqual(int(json.dumps(num)), num)
- self.assertEqual(json.loads(json.dumps(num)), num)
- self.assertEqual(json.loads(unicode(json.dumps(num))), num)
+ self.assertEqual(self.dumps(num), str(num))
+ self.assertEqual(int(self.dumps(num)), num)
+ self.assertEqual(self.loads(self.dumps(num)), num)
+ self.assertEqual(self.loads(unicode(self.dumps(num))), num)
+
+
+class TestPyFloat(TestFloat, PyTest): pass
+class TestCFloat(TestFloat, CTest): pass
diff --git a/Lib/json/tests/test_indent.py b/Lib/json/tests/test_indent.py
index 64b9b9c..9b18761 100644
--- a/Lib/json/tests/test_indent.py
+++ b/Lib/json/tests/test_indent.py
@@ -1,10 +1,9 @@
-from unittest import TestCase
-
-import json
import textwrap
from StringIO import StringIO
+from json.tests import PyTest, CTest
-class TestIndent(TestCase):
+
+class TestIndent(object):
def test_indent(self):
h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
{'nifty': 87}, {'field': 'yes', 'morefield': False} ]
@@ -31,11 +30,11 @@
]""")
- d1 = json.dumps(h)
- d2 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
+ d1 = self.dumps(h)
+ d2 = self.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
- h1 = json.loads(d1)
- h2 = json.loads(d2)
+ h1 = self.loads(d1)
+ h2 = self.loads(d2)
self.assertEqual(h1, h)
self.assertEqual(h2, h)
@@ -44,14 +43,18 @@
def test_indent0(self):
h = {3: 1}
def check(indent, expected):
- d1 = json.dumps(h, indent=indent)
+ d1 = self.dumps(h, indent=indent)
self.assertEqual(d1, expected)
sio = StringIO()
- json.dump(h, sio, indent=indent)
+ self.json.dump(h, sio, indent=indent)
self.assertEqual(sio.getvalue(), expected)
# indent=0 should emit newlines
check(0, '{\n"3": 1\n}')
# indent=None is more compact
check(None, '{"3": 1}')
+
+
+class TestPyIndent(TestIndent, PyTest): pass
+class TestCIndent(TestIndent, CTest): pass
diff --git a/Lib/json/tests/test_pass1.py b/Lib/json/tests/test_pass1.py
index 719c113..82d7154 100644
--- a/Lib/json/tests/test_pass1.py
+++ b/Lib/json/tests/test_pass1.py
@@ -1,6 +1,5 @@
-from unittest import TestCase
+from json.tests import PyTest, CTest
-import json
# from http://json.org/JSON_checker/test/pass1.json
JSON = r'''
@@ -62,15 +61,19 @@
,"rosebud"]
'''
-class TestPass1(TestCase):
+class TestPass1(object):
def test_parse(self):
# test in/out equivalence and parsing
- res = json.loads(JSON)
- out = json.dumps(res)
- self.assertEqual(res, json.loads(out))
+ res = self.loads(JSON)
+ out = self.dumps(res)
+ self.assertEqual(res, self.loads(out))
try:
- json.dumps(res, allow_nan=False)
+ self.dumps(res, allow_nan=False)
except ValueError:
pass
else:
self.fail("23456789012E666 should be out of range")
+
+
+class TestPyPass1(TestPass1, PyTest): pass
+class TestCPass1(TestPass1, CTest): pass
diff --git a/Lib/json/tests/test_pass2.py b/Lib/json/tests/test_pass2.py
index 379117e..a2bb6d7 100644
--- a/Lib/json/tests/test_pass2.py
+++ b/Lib/json/tests/test_pass2.py
@@ -1,14 +1,18 @@
-from unittest import TestCase
-import json
+from json.tests import PyTest, CTest
+
# from http://json.org/JSON_checker/test/pass2.json
JSON = r'''
[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
'''
-class TestPass2(TestCase):
+class TestPass2(object):
def test_parse(self):
# test in/out equivalence and parsing
- res = json.loads(JSON)
- out = json.dumps(res)
- self.assertEqual(res, json.loads(out))
+ res = self.loads(JSON)
+ out = self.dumps(res)
+ self.assertEqual(res, self.loads(out))
+
+
+class TestPyPass2(TestPass2, PyTest): pass
+class TestCPass2(TestPass2, CTest): pass
diff --git a/Lib/json/tests/test_pass3.py b/Lib/json/tests/test_pass3.py
index 9151c43..221f9a0 100644
--- a/Lib/json/tests/test_pass3.py
+++ b/Lib/json/tests/test_pass3.py
@@ -1,6 +1,5 @@
-from unittest import TestCase
+from json.tests import PyTest, CTest
-import json
# from http://json.org/JSON_checker/test/pass3.json
JSON = r'''
@@ -12,9 +11,14 @@
}
'''
-class TestPass3(TestCase):
+
+class TestPass3(object):
def test_parse(self):
# test in/out equivalence and parsing
- res = json.loads(JSON)
- out = json.dumps(res)
- self.assertEqual(res, json.loads(out))
+ res = self.loads(JSON)
+ out = self.dumps(res)
+ self.assertEqual(res, self.loads(out))
+
+
+class TestPyPass3(TestPass3, PyTest): pass
+class TestCPass3(TestPass3, CTest): pass
diff --git a/Lib/json/tests/test_recursion.py b/Lib/json/tests/test_recursion.py
index 1e9b8ab..b5221e5 100644
--- a/Lib/json/tests/test_recursion.py
+++ b/Lib/json/tests/test_recursion.py
@@ -1,28 +1,16 @@
-from unittest import TestCase
+from json.tests import PyTest, CTest
-import json
class JSONTestObject:
pass
-class RecursiveJSONEncoder(json.JSONEncoder):
- recurse = False
- def default(self, o):
- if o is JSONTestObject:
- if self.recurse:
- return [JSONTestObject]
- else:
- return 'JSONTestObject'
- return json.JSONEncoder.default(o)
-
-
-class TestRecursion(TestCase):
+class TestRecursion(object):
def test_listrecursion(self):
x = []
x.append(x)
try:
- json.dumps(x)
+ self.dumps(x)
except ValueError:
pass
else:
@@ -31,7 +19,7 @@
y = [x]
x.append(y)
try:
- json.dumps(x)
+ self.dumps(x)
except ValueError:
pass
else:
@@ -39,13 +27,13 @@
y = []
x = [y, y]
# ensure that the marker is cleared
- json.dumps(x)
+ self.dumps(x)
def test_dictrecursion(self):
x = {}
x["test"] = x
try:
- json.dumps(x)
+ self.dumps(x)
except ValueError:
pass
else:
@@ -53,9 +41,19 @@
x = {}
y = {"a": x, "b": x}
# ensure that the marker is cleared
- json.dumps(x)
+ self.dumps(x)
def test_defaultrecursion(self):
+ class RecursiveJSONEncoder(self.json.JSONEncoder):
+ recurse = False
+ def default(self, o):
+ if o is JSONTestObject:
+ if self.recurse:
+ return [JSONTestObject]
+ else:
+ return 'JSONTestObject'
+ return pyjson.JSONEncoder.default(o)
+
enc = RecursiveJSONEncoder()
self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"')
enc.recurse = True
@@ -65,3 +63,46 @@
pass
else:
self.fail("didn't raise ValueError on default recursion")
+
+
+ def test_highly_nested_objects_decoding(self):
+ # test that loading highly-nested objects doesn't segfault when C
+ # accelerations are used. See #12017
+ # str
+ with self.assertRaises(RuntimeError):
+ self.loads('{"a":' * 100000 + '1' + '}' * 100000)
+ with self.assertRaises(RuntimeError):
+ self.loads('{"a":' * 100000 + '[1]' + '}' * 100000)
+ with self.assertRaises(RuntimeError):
+ self.loads('[' * 100000 + '1' + ']' * 100000)
+ # unicode
+ with self.assertRaises(RuntimeError):
+ self.loads(u'{"a":' * 100000 + u'1' + u'}' * 100000)
+ with self.assertRaises(RuntimeError):
+ self.loads(u'{"a":' * 100000 + u'[1]' + u'}' * 100000)
+ with self.assertRaises(RuntimeError):
+ self.loads(u'[' * 100000 + u'1' + u']' * 100000)
+
+ def test_highly_nested_objects_encoding(self):
+ # See #12051
+ l, d = [], {}
+ for x in xrange(100000):
+ l, d = [l], {'k':d}
+ with self.assertRaises(RuntimeError):
+ self.dumps(l)
+ with self.assertRaises(RuntimeError):
+ self.dumps(d)
+
+ def test_endless_recursion(self):
+ # See #12051
+ class EndlessJSONEncoder(self.json.JSONEncoder):
+ def default(self, o):
+ """If check_circular is False, this will keep adding another list."""
+ return [o]
+
+ with self.assertRaises(RuntimeError):
+ EndlessJSONEncoder(check_circular=False).encode(5j)
+
+
+class TestPyRecursion(TestRecursion, PyTest): pass
+class TestCRecursion(TestRecursion, CTest): pass
diff --git a/Lib/json/tests/test_scanstring.py b/Lib/json/tests/test_scanstring.py
index d858161..4fef8cb 100644
--- a/Lib/json/tests/test_scanstring.py
+++ b/Lib/json/tests/test_scanstring.py
@@ -1,23 +1,10 @@
import sys
-from unittest import TestCase, skipUnless
+from json.tests import PyTest, CTest
-import json
-import json.decoder
-try:
- import _json
-except ImportError:
- _json = None
-
-class TestScanString(TestCase):
- def test_py_scanstring(self):
- self._test_scanstring(json.decoder.py_scanstring)
-
- @skipUnless(_json, 'test requires the _json module')
- def test_c_scanstring(self):
- self._test_scanstring(json.decoder.c_scanstring)
-
- def _test_scanstring(self, scanstring):
+class TestScanstring(object):
+ def test_scanstring(self):
+ scanstring = self.json.decoder.scanstring
self.assertEqual(
scanstring('"z\\ud834\\udd20x"', 1, None, True),
(u'z\U0001d120x', 16))
@@ -108,10 +95,15 @@
(u'Bad value', 12))
def test_issue3623(self):
- self.assertRaises(ValueError, json.decoder.scanstring, b"xxx", 1,
+ self.assertRaises(ValueError, self.json.decoder.scanstring, b"xxx", 1,
"xxx")
self.assertRaises(UnicodeDecodeError,
- json.encoder.encode_basestring_ascii, b"xx\xff")
+ self.json.encoder.encode_basestring_ascii, b"xx\xff")
def test_overflow(self):
- self.assertRaises(OverflowError, json.decoder.scanstring, b"xxx", sys.maxsize+1)
+ with self.assertRaises(OverflowError):
+ self.json.decoder.scanstring(b"xxx", sys.maxsize+1)
+
+
+class TestPyScanstring(TestScanstring, PyTest): pass
+class TestCScanstring(TestScanstring, CTest): pass
diff --git a/Lib/json/tests/test_separators.py b/Lib/json/tests/test_separators.py
index d5b92bd..a4246e1 100644
--- a/Lib/json/tests/test_separators.py
+++ b/Lib/json/tests/test_separators.py
@@ -1,10 +1,8 @@
import textwrap
-from unittest import TestCase
-
-import json
+from json.tests import PyTest, CTest
-class TestSeparators(TestCase):
+class TestSeparators(object):
def test_separators(self):
h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
{'nifty': 87}, {'field': 'yes', 'morefield': False} ]
@@ -31,12 +29,16 @@
]""")
- d1 = json.dumps(h)
- d2 = json.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : '))
+ d1 = self.dumps(h)
+ d2 = self.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : '))
- h1 = json.loads(d1)
- h2 = json.loads(d2)
+ h1 = self.loads(d1)
+ h2 = self.loads(d2)
self.assertEqual(h1, h)
self.assertEqual(h2, h)
self.assertEqual(d2, expect)
+
+
+class TestPySeparators(TestSeparators, PyTest): pass
+class TestCSeparators(TestSeparators, CTest): pass
diff --git a/Lib/json/tests/test_speedups.py b/Lib/json/tests/test_speedups.py
index 1505065..7186a40 100644
--- a/Lib/json/tests/test_speedups.py
+++ b/Lib/json/tests/test_speedups.py
@@ -1,29 +1,23 @@
-from unittest import TestCase, skipUnless
+from json.tests import CTest
-from json import decoder, encoder, scanner
-try:
- import _json
-except ImportError:
- _json = None
-
-@skipUnless(_json, 'test requires the _json module')
-class TestSpeedups(TestCase):
+class TestSpeedups(CTest):
def test_scanstring(self):
- self.assertEqual(decoder.scanstring.__module__, "_json")
- self.assertIs(decoder.scanstring, decoder.c_scanstring)
+ self.assertEqual(self.json.decoder.scanstring.__module__, "_json")
+ self.assertIs(self.json.decoder.scanstring, self.json.decoder.c_scanstring)
def test_encode_basestring_ascii(self):
- self.assertEqual(encoder.encode_basestring_ascii.__module__, "_json")
- self.assertIs(encoder.encode_basestring_ascii,
- encoder.c_encode_basestring_ascii)
+ self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
+ "_json")
+ self.assertIs(self.json.encoder.encode_basestring_ascii,
+ self.json.encoder.c_encode_basestring_ascii)
-class TestDecode(TestCase):
+class TestDecode(CTest):
def test_make_scanner(self):
- self.assertRaises(AttributeError, scanner.c_make_scanner, 1)
+ self.assertRaises(AttributeError, self.json.scanner.c_make_scanner, 1)
def test_make_encoder(self):
- self.assertRaises(TypeError, encoder.c_make_encoder,
+ self.assertRaises(TypeError, self.json.encoder.c_make_encoder,
None,
"\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75",
None)
diff --git a/Lib/json/tests/test_unicode.py b/Lib/json/tests/test_unicode.py
index ad7fe24..31cf389 100644
--- a/Lib/json/tests/test_unicode.py
+++ b/Lib/json/tests/test_unicode.py
@@ -1,11 +1,10 @@
-from unittest import TestCase
-
-import json
from collections import OrderedDict
+from json.tests import PyTest, CTest
-class TestUnicode(TestCase):
+
+class TestUnicode(object):
def test_encoding1(self):
- encoder = json.JSONEncoder(encoding='utf-8')
+ encoder = self.json.JSONEncoder(encoding='utf-8')
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
s = u.encode('utf-8')
ju = encoder.encode(u)
@@ -15,68 +14,72 @@
def test_encoding2(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
s = u.encode('utf-8')
- ju = json.dumps(u, encoding='utf-8')
- js = json.dumps(s, encoding='utf-8')
+ ju = self.dumps(u, encoding='utf-8')
+ js = self.dumps(s, encoding='utf-8')
self.assertEqual(ju, js)
def test_encoding3(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
- j = json.dumps(u)
+ j = self.dumps(u)
self.assertEqual(j, '"\\u03b1\\u03a9"')
def test_encoding4(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
- j = json.dumps([u])
+ j = self.dumps([u])
self.assertEqual(j, '["\\u03b1\\u03a9"]')
def test_encoding5(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
- j = json.dumps(u, ensure_ascii=False)
+ j = self.dumps(u, ensure_ascii=False)
self.assertEqual(j, u'"{0}"'.format(u))
def test_encoding6(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
- j = json.dumps([u], ensure_ascii=False)
+ j = self.dumps([u], ensure_ascii=False)
self.assertEqual(j, u'["{0}"]'.format(u))
def test_big_unicode_encode(self):
u = u'\U0001d120'
- self.assertEqual(json.dumps(u), '"\\ud834\\udd20"')
- self.assertEqual(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')
+ self.assertEqual(self.dumps(u), '"\\ud834\\udd20"')
+ self.assertEqual(self.dumps(u, ensure_ascii=False), u'"\U0001d120"')
def test_big_unicode_decode(self):
u = u'z\U0001d120x'
- self.assertEqual(json.loads('"' + u + '"'), u)
- self.assertEqual(json.loads('"z\\ud834\\udd20x"'), u)
+ self.assertEqual(self.loads('"' + u + '"'), u)
+ self.assertEqual(self.loads('"z\\ud834\\udd20x"'), u)
def test_unicode_decode(self):
for i in range(0, 0xd7ff):
u = unichr(i)
s = '"\\u{0:04x}"'.format(i)
- self.assertEqual(json.loads(s), u)
+ self.assertEqual(self.loads(s), u)
def test_object_pairs_hook_with_unicode(self):
s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4),
(u"qrt", 5), (u"pad", 6), (u"hoy", 7)]
- self.assertEqual(json.loads(s), eval(s))
- self.assertEqual(json.loads(s, object_pairs_hook = lambda x: x), p)
- od = json.loads(s, object_pairs_hook = OrderedDict)
+ self.assertEqual(self.loads(s), eval(s))
+ self.assertEqual(self.loads(s, object_pairs_hook = lambda x: x), p)
+ od = self.loads(s, object_pairs_hook = OrderedDict)
self.assertEqual(od, OrderedDict(p))
self.assertEqual(type(od), OrderedDict)
# the object_pairs_hook takes priority over the object_hook
- self.assertEqual(json.loads(s,
+ self.assertEqual(self.loads(s,
object_pairs_hook = OrderedDict,
object_hook = lambda x: None),
OrderedDict(p))
def test_default_encoding(self):
- self.assertEqual(json.loads(u'{"a": "\xe9"}'.encode('utf-8')),
+ self.assertEqual(self.loads(u'{"a": "\xe9"}'.encode('utf-8')),
{'a': u'\xe9'})
def test_unicode_preservation(self):
- self.assertEqual(type(json.loads(u'""')), unicode)
- self.assertEqual(type(json.loads(u'"a"')), unicode)
- self.assertEqual(type(json.loads(u'["a"]')[0]), unicode)
+ self.assertEqual(type(self.loads(u'""')), unicode)
+ self.assertEqual(type(self.loads(u'"a"')), unicode)
+ self.assertEqual(type(self.loads(u'["a"]')[0]), unicode)
# Issue 10038.
- self.assertEqual(type(json.loads('"foo"')), unicode)
+ self.assertEqual(type(self.loads('"foo"')), unicode)
+
+
+class TestPyUnicode(TestUnicode, PyTest): pass
+class TestCUnicode(TestUnicode, CTest): pass
diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py
index 81d3ef2..586129a 100644
--- a/Lib/lib-tk/Tkinter.py
+++ b/Lib/lib-tk/Tkinter.py
@@ -30,7 +30,7 @@
tk.mainloop()
"""
-__version__ = "$Revision$"
+__version__ = "$Revision: 81008 $"
import sys
if sys.platform == "win32":
diff --git a/Lib/lib-tk/test/runtktests.py b/Lib/lib-tk/test/runtktests.py
index 402c342..95e1728 100644
--- a/Lib/lib-tk/test/runtktests.py
+++ b/Lib/lib-tk/test/runtktests.py
@@ -14,6 +14,49 @@
this_dir_path = os.path.abspath(os.path.dirname(__file__))
+_tk_unavailable = None
+
+def check_tk_availability():
+ """Check that Tk is installed and available."""
+ global _tk_unavailable
+
+ if _tk_unavailable is None:
+ _tk_unavailable = False
+ if sys.platform == 'darwin':
+ # The Aqua Tk implementations on OS X can abort the process if
+ # being called in an environment where a window server connection
+ # cannot be made, for instance when invoked by a buildbot or ssh
+ # process not running under the same user id as the current console
+ # user. To avoid that, raise an exception if the window manager
+ # connection is not available.
+ from ctypes import cdll, c_int, pointer, Structure
+ from ctypes.util import find_library
+
+ app_services = cdll.LoadLibrary(find_library("ApplicationServices"))
+
+ if app_services.CGMainDisplayID() == 0:
+ _tk_unavailable = "cannot run without OS X window manager"
+ else:
+ class ProcessSerialNumber(Structure):
+ _fields_ = [("highLongOfPSN", c_int),
+ ("lowLongOfPSN", c_int)]
+ psn = ProcessSerialNumber()
+ psn_p = pointer(psn)
+ if ( (app_services.GetCurrentProcess(psn_p) < 0) or
+ (app_services.SetFrontProcess(psn_p) < 0) ):
+ _tk_unavailable = "cannot run without OS X gui process"
+ else: # not OS X
+ import Tkinter
+ try:
+ Tkinter.Button()
+ except Tkinter.TclError as msg:
+ # assuming tk is not available
+ _tk_unavailable = "tk not available: %s" % msg
+
+ if _tk_unavailable:
+ raise unittest.SkipTest(_tk_unavailable)
+ return
+
def is_package(path):
for name in os.listdir(path):
if name in ('__init__.py', '__init__.pyc', '__init.pyo'):
diff --git a/Lib/lib-tk/test/test_ttk/test_widgets.py b/Lib/lib-tk/test/test_ttk/test_widgets.py
index 236323c..aca90cf 100644
--- a/Lib/lib-tk/test/test_ttk/test_widgets.py
+++ b/Lib/lib-tk/test/test_ttk/test_widgets.py
@@ -2,6 +2,7 @@
import Tkinter
import ttk
from test.test_support import requires, run_unittest
+import sys
import support
from test_functions import MockTclObj, MockStateSpec
@@ -560,11 +561,19 @@
self.nb.pack()
self.nb.wait_visibility()
- self.assertEqual(self.nb.tab('@5,5'), self.nb.tab('current'))
+ if sys.platform == 'darwin':
+ tb_idx = "@20,5"
+ else:
+ tb_idx = "@5,5"
+ self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current'))
for i in range(5, 100, 5):
- if self.nb.tab('@%d, 5' % i, text=None) == 'a':
- break
+ try:
+ if self.nb.tab('@%d, 5' % i, text=None) == 'a':
+ break
+ except Tkinter.TclError:
+ pass
+
else:
self.fail("Tab with text 'a' not found")
@@ -721,7 +730,10 @@
self.nb.enable_traversal()
self.nb.focus_force()
support.simulate_mouse_click(self.nb, 5, 5)
- self.nb.event_generate('<Alt-a>')
+ if sys.platform == 'darwin':
+ self.nb.event_generate('<Option-a>')
+ else:
+ self.nb.event_generate('<Alt-a>')
self.assertEqual(self.nb.select(), str(self.child1))
@@ -925,7 +937,8 @@
self.assertRaises(Tkinter.TclError, self.tv.heading, '#0',
anchor=1)
-
+ # XXX skipping for now; should be fixed to work with newer ttk
+ @unittest.skip("skipping pending resolution of Issue #10734")
def test_heading_callback(self):
def simulate_heading_click(x, y):
support.simulate_mouse_click(self.tv, x, y)
diff --git a/Lib/lib-tk/turtle.py b/Lib/lib-tk/turtle.py
index a003433..4230d68 100644
--- a/Lib/lib-tk/turtle.py
+++ b/Lib/lib-tk/turtle.py
@@ -27,10 +27,10 @@
kids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.
-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it
+Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
the direction it is facing, drawing a line as it moves. Give it the
-command turtle.left(25), and it rotates in-place 25 degrees clockwise.
+command turtle.right(25), and it rotates in-place 25 degrees clockwise.
By combining together these and similar commands, intricate shapes and
pictures can easily be drawn.
diff --git a/Lib/lib2to3/tests/test_refactor.py b/Lib/lib2to3/tests/test_refactor.py
index 3eecde8..9773fc9 100644
--- a/Lib/lib2to3/tests/test_refactor.py
+++ b/Lib/lib2to3/tests/test_refactor.py
@@ -177,22 +177,26 @@
self.assertEqual(results, expected)
def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS):
+ tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor")
+ self.addCleanup(shutil.rmtree, tmpdir)
+ # make a copy of the tested file that we can write to
+ shutil.copy(test_file, tmpdir)
+ test_file = os.path.join(tmpdir, os.path.basename(test_file))
+ os.chmod(test_file, 0o644)
+
def read_file():
with open(test_file, "rb") as fp:
return fp.read()
+
old_contents = read_file()
rt = self.rt(fixers=fixers)
rt.refactor_file(test_file)
self.assertEqual(old_contents, read_file())
- try:
- rt.refactor_file(test_file, True)
- new_contents = read_file()
- self.assertNotEqual(old_contents, new_contents)
- finally:
- with open(test_file, "wb") as fp:
- fp.write(old_contents)
+ rt.refactor_file(test_file, True)
+ new_contents = read_file()
+ self.assertNotEqual(old_contents, new_contents)
return new_contents
def test_refactor_file(self):
diff --git a/Lib/locale.py b/Lib/locale.py
index 921f4f6..0c4d652 100644
--- a/Lib/locale.py
+++ b/Lib/locale.py
@@ -331,6 +331,13 @@
# overridden below)
_setlocale = setlocale
+# Avoid relying on the locale-dependent .lower() method
+# (see issue #1813).
+_ascii_lower_map = ''.join(
+ chr(x + 32 if x >= ord('A') and x <= ord('Z') else x)
+ for x in range(256)
+)
+
def normalize(localename):
""" Returns a normalized locale code for the given locale
@@ -348,7 +355,9 @@
"""
# Normalize the locale name and extract the encoding
- fullname = localename.lower()
+ if isinstance(localename, unicode):
+ localename = localename.encode('ascii')
+ fullname = localename.translate(_ascii_lower_map)
if ':' in fullname:
# ':' is sometimes used as encoding delimiter.
fullname = fullname.replace(':', '.')
@@ -621,7 +630,7 @@
'tactis': 'TACTIS',
'euc_jp': 'eucJP',
'euc_kr': 'eucKR',
- 'utf_8': 'UTF8',
+ 'utf_8': 'UTF-8',
'koi8_r': 'KOI8-R',
'koi8_u': 'KOI8-U',
# XXX This list is still incomplete. If you know more
diff --git a/Lib/mailbox.py b/Lib/mailbox.py
index b74eeb5..a9d9c28 100644
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -234,19 +234,24 @@
def __init__(self, dirname, factory=rfc822.Message, create=True):
"""Initialize a Maildir instance."""
Mailbox.__init__(self, dirname, factory, create)
+ self._paths = {
+ 'tmp': os.path.join(self._path, 'tmp'),
+ 'new': os.path.join(self._path, 'new'),
+ 'cur': os.path.join(self._path, 'cur'),
+ }
if not os.path.exists(self._path):
if create:
os.mkdir(self._path, 0700)
- os.mkdir(os.path.join(self._path, 'tmp'), 0700)
- os.mkdir(os.path.join(self._path, 'new'), 0700)
- os.mkdir(os.path.join(self._path, 'cur'), 0700)
+ for path in self._paths.values():
+ os.mkdir(path, 0o700)
else:
raise NoSuchMailboxError(self._path)
self._toc = {}
- self._last_read = None # Records last time we read cur/new
- # NOTE: we manually invalidate _last_read each time we do any
- # modifications ourselves, otherwise we might get tripped up by
- # bogus mtime behaviour on some systems (see issue #6896).
+ self._toc_mtimes = {}
+ for subdir in ('cur', 'new'):
+ self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir])
+ self._last_read = time.time() # Records last time we read cur/new
+ self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
def add(self, message):
"""Add message and return assigned key."""
@@ -283,15 +288,11 @@
raise
if isinstance(message, MaildirMessage):
os.utime(dest, (os.path.getatime(dest), message.get_date()))
- # Invalidate cached toc
- self._last_read = None
return uniq
def remove(self, key):
"""Remove the keyed message; raise KeyError if it doesn't exist."""
os.remove(os.path.join(self._path, self._lookup(key)))
- # Invalidate cached toc (only on success)
- self._last_read = None
def discard(self, key):
"""If the keyed message exists, remove it."""
@@ -326,8 +327,6 @@
if isinstance(message, MaildirMessage):
os.utime(new_path, (os.path.getatime(new_path),
message.get_date()))
- # Invalidate cached toc
- self._last_read = None
def get_message(self, key):
"""Return a Message representation or raise a KeyError."""
@@ -383,8 +382,8 @@
def flush(self):
"""Write any pending changes to disk."""
# Maildir changes are always written immediately, so there's nothing
- # to do except invalidate our cached toc.
- self._last_read = None
+ # to do.
+ pass
def lock(self):
"""Lock the mailbox."""
@@ -482,36 +481,39 @@
def _refresh(self):
"""Update table of contents mapping."""
- if self._last_read is not None:
- for subdir in ('new', 'cur'):
- mtime = os.path.getmtime(os.path.join(self._path, subdir))
- if mtime > self._last_read:
- break
- else:
+ # If it has been less than two seconds since the last _refresh() call,
+ # we have to unconditionally re-read the mailbox just in case it has
+ # been modified, because os.path.mtime() has a 2 sec resolution in the
+ # most common worst case (FAT) and a 1 sec resolution typically. This
+ # results in a few unnecessary re-reads when _refresh() is called
+ # multiple times in that interval, but once the clock ticks over, we
+ # will only re-read as needed. Because the filesystem might be being
+ # served by an independent system with its own clock, we record and
+ # compare with the mtimes from the filesystem. Because the other
+ # system's clock might be skewing relative to our clock, we add an
+ # extra delta to our wait. The default is one tenth second, but is an
+ # instance variable and so can be adjusted if dealing with a
+ # particularly skewed or irregular system.
+ if time.time() - self._last_read > 2 + self._skewfactor:
+ refresh = False
+ for subdir in self._toc_mtimes:
+ mtime = os.path.getmtime(self._paths[subdir])
+ if mtime > self._toc_mtimes[subdir]:
+ refresh = True
+ self._toc_mtimes[subdir] = mtime
+ if not refresh:
return
-
- # We record the current time - 1sec so that, if _refresh() is called
- # again in the same second, we will always re-read the mailbox
- # just in case it's been modified. (os.path.mtime() only has
- # 1sec resolution.) This results in a few unnecessary re-reads
- # when _refresh() is called multiple times in the same second,
- # but once the clock ticks over, we will only re-read as needed.
- now = time.time() - 1
-
+ # Refresh toc
self._toc = {}
- def update_dir (subdir):
- path = os.path.join(self._path, subdir)
+ for subdir in self._toc_mtimes:
+ path = self._paths[subdir]
for entry in os.listdir(path):
p = os.path.join(path, entry)
if os.path.isdir(p):
continue
uniq = entry.split(self.colon)[0]
self._toc[uniq] = os.path.join(subdir, entry)
-
- update_dir('new')
- update_dir('cur')
-
- self._last_read = now
+ self._last_read = time.time()
def _lookup(self, key):
"""Use TOC to return subpath for given key, or raise a KeyError."""
@@ -1852,7 +1854,10 @@
def close(self):
"""Close the file."""
- del self._file
+ if hasattr(self, '_file'):
+ if hasattr(self._file, 'close'):
+ self._file.close()
+ del self._file
def _read(self, size, read_method):
"""Read size bytes using read_method."""
@@ -1896,6 +1901,12 @@
size = remaining
return _ProxyFile._read(self, size, read_method)
+ def close(self):
+ # do *not* close the underlying file object for partial files,
+ # since it's global to the mailbox object
+ if hasattr(self, '_file'):
+ del self._file
+
def _lock_file(f, dotlock=True):
"""Lock file f using lockf and dot locking."""
diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py
index 4c054c9..8347786 100644
--- a/Lib/mimetypes.py
+++ b/Lib/mimetypes.py
@@ -432,6 +432,7 @@
'.hdf' : 'application/x-hdf',
'.htm' : 'text/html',
'.html' : 'text/html',
+ '.ico' : 'image/vnd.microsoft.icon',
'.ief' : 'image/ief',
'.jpe' : 'image/jpeg',
'.jpeg' : 'image/jpeg',
diff --git a/Lib/multiprocessing/heap.py b/Lib/multiprocessing/heap.py
index 52ee49d..a1f3711 100644
--- a/Lib/multiprocessing/heap.py
+++ b/Lib/multiprocessing/heap.py
@@ -101,6 +101,8 @@
self._stop_to_block = {}
self._allocated_blocks = set()
self._arenas = []
+ # list of pending blocks to free - see free() comment below
+ self._pending_free_blocks = []
@staticmethod
def _roundup(n, alignment):
@@ -175,15 +177,39 @@
return start, stop
- def free(self, block):
- # free a block returned by malloc()
- assert os.getpid() == self._lastpid
- self._lock.acquire()
- try:
+ def _free_pending_blocks(self):
+ # Free all the blocks in the pending list - called with the lock held.
+ while True:
+ try:
+ block = self._pending_free_blocks.pop()
+ except IndexError:
+ break
self._allocated_blocks.remove(block)
self._free(block)
- finally:
- self._lock.release()
+
+ def free(self, block):
+ # free a block returned by malloc()
+ # Since free() can be called asynchronously by the GC, it could happen
+ # that it's called while self._lock is held: in that case,
+ # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
+ # trylock is used instead, and if the lock can't be acquired
+ # immediately, the block is added to a list of blocks to be freed
+ # synchronously sometimes later from malloc() or free(), by calling
+ # _free_pending_blocks() (appending and retrieving from a list is not
+ # strictly thread-safe but under cPython it's atomic thanks to the GIL).
+ assert os.getpid() == self._lastpid
+ if not self._lock.acquire(False):
+ # can't acquire the lock right now, add the block to the list of
+ # pending blocks to free
+ self._pending_free_blocks.append(block)
+ else:
+ # we hold the lock
+ try:
+ self._free_pending_blocks()
+ self._allocated_blocks.remove(block)
+ self._free(block)
+ finally:
+ self._lock.release()
def malloc(self, size):
# return a block of right size (possibly rounded up)
@@ -191,6 +217,7 @@
if os.getpid() != self._lastpid:
self.__init__() # reinitialize after fork
self._lock.acquire()
+ self._free_pending_blocks()
try:
size = self._roundup(max(size,1), self._alignment)
(arena, start, stop) = self._malloc(size)
diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py
index 862a60e..c66876a 100644
--- a/Lib/multiprocessing/pool.py
+++ b/Lib/multiprocessing/pool.py
@@ -125,6 +125,8 @@
processes = cpu_count()
except NotImplementedError:
processes = 1
+ if processes < 1:
+ raise ValueError("Number of processes must be at least 1")
if initializer is not None and not hasattr(initializer, '__call__'):
raise TypeError('initializer must be a callable')
diff --git a/Lib/multiprocessing/queues.py b/Lib/multiprocessing/queues.py
index 8584408..b7eecef 100644
--- a/Lib/multiprocessing/queues.py
+++ b/Lib/multiprocessing/queues.py
@@ -188,13 +188,7 @@
debug('... done self._thread.start()')
# On process exit we will wait for data to be flushed to pipe.
- #
- # However, if this process created the queue then all
- # processes which use the queue will be descendants of this
- # process. Therefore waiting for the queue to be flushed
- # is pointless once all the child processes have been joined.
- created_by_this_process = (self._opid == os.getpid())
- if not self._joincancelled and not created_by_this_process:
+ if not self._joincancelled:
self._jointhread = Finalize(
self._thread, Queue._finalize_join,
[weakref.ref(self._thread)],
diff --git a/Lib/netrc.py b/Lib/netrc.py
index 4caeb96..0fd37e3 100644
--- a/Lib/netrc.py
+++ b/Lib/netrc.py
@@ -41,8 +41,12 @@
if not tt:
break
elif tt[0] == '#':
- fp.readline();
- continue;
+ # seek to beginning of comment, in case reading the token put
+ # us on a new line, and then skip the rest of the line.
+ pos = len(tt) + 1
+ lexer.instream.seek(-pos, 1)
+ lexer.instream.readline()
+ continue
elif tt == 'machine':
entryname = lexer.get_token()
elif tt == 'default':
@@ -68,8 +72,8 @@
self.hosts[entryname] = {}
while 1:
tt = lexer.get_token()
- if (tt=='' or tt == 'machine' or
- tt == 'default' or tt =='macdef'):
+ if (tt.startswith('#') or
+ tt in {'', 'machine', 'default', 'macdef'}):
if password:
self.hosts[entryname] = (login, account, password)
lexer.push_token(tt)
diff --git a/Lib/ntpath.py b/Lib/ntpath.py
index 765e1bf..4f8f423 100644
--- a/Lib/ntpath.py
+++ b/Lib/ntpath.py
@@ -521,3 +521,13 @@
if not rel_list:
return curdir
return join(*rel_list)
+
+try:
+ # The genericpath.isdir implementation uses os.stat and checks the mode
+ # attribute to tell whether or not the path is a directory.
+ # This is overkill on Windows - just pass the path to GetFileAttributes
+ # and check the attribute from there.
+ from nt import _isdir as isdir
+except ImportError:
+ # Use genericpath.isdir as imported above.
+ pass
diff --git a/Lib/optparse.py b/Lib/optparse.py
index 87d7737..731a2bb 100644
--- a/Lib/optparse.py
+++ b/Lib/optparse.py
@@ -1131,6 +1131,11 @@
prog : string
the name of the current program (to override
os.path.basename(sys.argv[0])).
+ description : string
+ A paragraph of text giving a brief overview of your program.
+ optparse reformats this paragraph to fit the current terminal
+ width and prints it when the user requests help (after usage,
+ but before the list of options).
epilog : string
paragraph of help text to print after option help
diff --git a/Lib/pickle.py b/Lib/pickle.py
index 8c5d51f..5b95cba 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -24,7 +24,7 @@
"""
-__version__ = "$Revision$" # Code version
+__version__ = "$Revision: 72223 $" # Code version
from types import *
from copy_reg import dispatch_table
@@ -286,20 +286,20 @@
f(self, obj) # Call unbound method with explicit self
return
- # Check for a class with a custom metaclass; treat as regular class
- try:
- issc = issubclass(t, TypeType)
- except TypeError: # t is not a class (old Boost; see SF #502085)
- issc = 0
- if issc:
- self.save_global(obj)
- return
-
# Check copy_reg.dispatch_table
reduce = dispatch_table.get(t)
if reduce:
rv = reduce(obj)
else:
+ # Check for a class with a custom metaclass; treat as regular class
+ try:
+ issc = issubclass(t, TypeType)
+ except TypeError: # t is not a class (old Boost; see SF #502085)
+ issc = 0
+ if issc:
+ self.save_global(obj)
+ return
+
# Check for a __reduce_ex__ method, fall back to __reduce__
reduce = getattr(obj, "__reduce_ex__", None)
if reduce:
diff --git a/Lib/pipes.py b/Lib/pipes.py
index 02e1257..26750f6 100644
--- a/Lib/pipes.py
+++ b/Lib/pipes.py
@@ -54,8 +54,6 @@
To create a new template object initialized to a given one:
t2 = t.clone()
-
-For an example, see the function test() at the end of the file.
""" # '
diff --git a/Lib/pkgutil.py b/Lib/pkgutil.py
index c50928f..ce072ec 100644
--- a/Lib/pkgutil.py
+++ b/Lib/pkgutil.py
@@ -11,7 +11,7 @@
__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
- 'walk_packages', 'iter_modules',
+ 'walk_packages', 'iter_modules', 'get_data',
'ImpImporter', 'ImpLoader', 'read_code', 'extend_path',
]
@@ -194,8 +194,11 @@
yielded = {}
import inspect
-
- filenames = os.listdir(self.path)
+ try:
+ filenames = os.listdir(self.path)
+ except OSError:
+ # ignore unreadable directories like import does
+ filenames = []
filenames.sort() # handle packages before same-named modules
for fn in filenames:
@@ -208,7 +211,12 @@
if not modname and os.path.isdir(path) and '.' not in fn:
modname = fn
- for fn in os.listdir(path):
+ try:
+ dircontents = os.listdir(path)
+ except OSError:
+ # ignore unreadable directories like import does
+ dircontents = []
+ for fn in dircontents:
subname = inspect.getmodulename(fn)
if subname=='__init__':
ispkg = True
diff --git a/Lib/plat-mac/findertools.py b/Lib/plat-mac/findertools.py
index 1363562..d0c74a9 100644
--- a/Lib/plat-mac/findertools.py
+++ b/Lib/plat-mac/findertools.py
@@ -128,7 +128,7 @@
def comment(object, comment=None):
"""comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window."""
object = Carbon.File.FSRef(object)
- object_alias = object.FSNewAliasMonimal()
+ object_alias = object.FSNewAliasMinimal()
if comment is None:
return _getcomment(object_alias)
else:
diff --git a/Lib/platform.py b/Lib/platform.py
index 3181303..710f21e 100755
--- a/Lib/platform.py
+++ b/Lib/platform.py
@@ -765,6 +765,7 @@
0x2: 'PowerPC',
0xa: 'i386'}.get(sysa,'')
+ versioninfo=('', '', '')
return release,versioninfo,machine
def _mac_ver_xml():
@@ -1448,9 +1449,10 @@
""" Returns a string identifying the Python implementation.
Currently, the following implementations are identified:
- 'CPython' (C implementation of Python),
- 'IronPython' (.NET implementation of Python),
- 'Jython' (Java implementation of Python).
+ 'CPython' (C implementation of Python),
+ 'IronPython' (.NET implementation of Python),
+ 'Jython' (Java implementation of Python),
+ 'PyPy' (Python implementation of Python).
"""
return _sys_version()[0]
diff --git a/Lib/profile.py b/Lib/profile.py
index 2d1f486..297aa04 100755
--- a/Lib/profile.py
+++ b/Lib/profile.py
@@ -2,35 +2,26 @@
#
# Class for profiling python code. rev 1.0 6/2/94
#
+# Written by James Roskind
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
"""Class for profiling Python code."""
-# Copyright 1994, by InfoSeek Corporation, all rights reserved.
-# Written by James Roskind
+# Copyright Disney Enterprises, Inc. All Rights Reserved.
+# Licensed to PSF under a Contributor Agreement
#
-# Permission to use, copy, modify, and distribute this Python software
-# and its associated documentation for any purpose (subject to the
-# restriction in the following sentence) without fee is hereby granted,
-# provided that the above copyright notice appears in all copies, and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation, and that the name of InfoSeek not be used in
-# advertising or publicity pertaining to distribution of the software
-# without specific, written prior permission. This permission is
-# explicitly restricted to the copying and modification of the software
-# to remain in Python, compiled Python, or other languages (such as C)
-# wherein the modified or derived code is exclusively imported into a
-# Python module.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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.
-
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+# either express or implied. See the License for the specific language
+# governing permissions and limitations under the License.
import sys
diff --git a/Lib/pstats.py b/Lib/pstats.py
index 9ccd75b..3dc61d6 100644
--- a/Lib/pstats.py
+++ b/Lib/pstats.py
@@ -1,35 +1,23 @@
"""Class for printing reports on profiled python code."""
-# Class for printing reports on profiled python code. rev 1.0 4/1/94
-#
+# Written by James Roskind
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
-#
-# see profile.py for more info.
-# Copyright 1994, by InfoSeek Corporation, all rights reserved.
-# Written by James Roskind
+# Copyright Disney Enterprises, Inc. All Rights Reserved.
+# Licensed to PSF under a Contributor Agreement
#
-# Permission to use, copy, modify, and distribute this Python software
-# and its associated documentation for any purpose (subject to the
-# restriction in the following sentence) without fee is hereby granted,
-# provided that the above copyright notice appears in all copies, and
-# that both that copyright notice and this permission notice appear in
-# supporting documentation, and that the name of InfoSeek not be used in
-# advertising or publicity pertaining to distribution of the software
-# without specific, written prior permission. This permission is
-# explicitly restricted to the copying and modification of the software
-# to remain in Python, compiled Python, or other languages (such as C)
-# wherein the modified or derived code is exclusively imported into a
-# Python module.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
#
-# INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-# FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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.
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+# either express or implied. See the License for the specific language
+# governing permissions and limitations under the License.
import sys
diff --git a/Lib/pydoc.py b/Lib/pydoc.py
index 8b6f7ee..d557790 100755
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -37,7 +37,7 @@
__author__ = "Ka-Ping Yee <ping@lfw.org>"
__date__ = "26 February 2001"
-__version__ = "$Revision$"
+__version__ = "$Revision: 88564 $"
__credits__ = """Guido van Rossum, for an excellent programming language.
Tommy Burnette, the original creator of manpy.
Paul Prescod, for all his work on onlinehelp.
@@ -52,7 +52,7 @@
# the current directory is changed with os.chdir(), an incorrect
# path will be displayed.
-import sys, imp, os, re, types, inspect, __builtin__, pkgutil
+import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
from repr import Repr
from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
from traceback import extract_tb
@@ -212,8 +212,8 @@
def synopsis(filename, cache={}):
"""Get the one-line summary out of a module file."""
mtime = os.stat(filename).st_mtime
- lastupdate, result = cache.get(filename, (0, None))
- if lastupdate < mtime:
+ lastupdate, result = cache.get(filename, (None, None))
+ if lastupdate is None or lastupdate < mtime:
info = inspect.getmoduleinfo(filename)
try:
file = open(filename)
@@ -478,9 +478,9 @@
def multicolumn(self, list, format, cols=4):
"""Format a list of items into a multi-column list."""
result = ''
- rows = (len(list)+cols-1)/cols
+ rows = (len(list)+cols-1)//cols
for col in range(cols):
- result = result + '<td width="%d%%" valign=top>' % (100/cols)
+ result = result + '<td width="%d%%" valign=top>' % (100//cols)
for i in range(rows*col, rows*col+rows):
if i < len(list):
result = result + format(list[i]) + '<br>\n'
@@ -1454,13 +1454,14 @@
else: break
if module:
object = module
- for part in parts[n:]:
- try: object = getattr(object, part)
- except AttributeError: return None
- return object
else:
- if hasattr(__builtin__, path):
- return getattr(__builtin__, path)
+ object = __builtin__
+ for part in parts[n:]:
+ try:
+ object = getattr(object, part)
+ except AttributeError:
+ return None
+ return object
# --------------------------------------- interactive interpreter interface
@@ -1967,10 +1968,11 @@
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
print modname, desc and '- ' + desc
- try: import warnings
- except ImportError: pass
- else: warnings.filterwarnings('ignore') # ignore problems during import
- ModuleScanner().run(callback, key)
+ def onerror(modname):
+ pass
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore') # ignore problems during import
+ ModuleScanner().run(callback, key, onerror=onerror)
# --------------------------------------------------- web browser interface
diff --git a/Lib/pydoc_data/topics.py b/Lib/pydoc_data/topics.py
index 849cd25..b1589ba 100644
--- a/Lib/pydoc_data/topics.py
+++ b/Lib/pydoc_data/topics.py
@@ -1,16 +1,16 @@
-# Autogenerated by Sphinx on Sat Jul 3 08:52:04 2010
+# Autogenerated by Sphinx on Sat Jun 11 09:49:30 2011
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\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n',
- 'assignment': 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 object\n must be an iterable with the same number of items as there are\n targets in the target list, and the items are assigned, from left to\n right, to the corresponding targets. (This rule is relaxed as of\n Python 1.5; in earlier versions, the object had to be a tuple.\n Since strings are sequences, an assignment like ``a, b = "xy"`` is\n now legal as long as the string has the right length.)\n\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 square\n brackets: The object must be an iterable with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n Note: If the object is a class instance and the attribute reference\n occurs on both sides of the assignment operator, the RHS expression,\n ``a.x`` can access either an instance attribute or (if no instance\n attribute exists) a class attribute. The LHS target ``a.x`` is\n always set as an instance attribute, creating it if necessary.\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n same attribute: if the RHS expression refers to a class attribute,\n the LHS creates a new instance attribute as the target of the\n assignment:\n\n class Cls:\n x = 3 # class variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\n\n This description does not necessarily apply to descriptor\n attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield 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 reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to (small) integers. If either\n bound is negative, the sequence\'s length is added to it. The\n resulting bounds are clipped to lie between zero and the sequence\'s\n length, inclusive. Finally, the sequence object is asked to replace\n the slice with the items of the assigned sequence. The length of\n the slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print x\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
+ '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 object\n must be an iterable with the same number of items as there are\n targets in the target list, and the items are assigned, from left to\n right, to the corresponding targets.\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 square\n brackets: The object must be an iterable with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n Note: If the object is a class instance and the attribute reference\n occurs on both sides of the assignment operator, the RHS expression,\n ``a.x`` can access either an instance attribute or (if no instance\n attribute exists) a class attribute. The LHS target ``a.x`` is\n always set as an instance attribute, creating it if necessary.\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n same attribute: if the RHS expression refers to a class attribute,\n the LHS creates a new instance attribute as the target of the\n assignment:\n\n class Cls:\n x = 3 # class variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\n\n This description does not necessarily apply to descriptor\n attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield 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 reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to (small) integers. If either\n bound is negative, the sequence\'s length is added to it. The\n resulting bounds are clipped to lie between zero and the sequence\'s\n length, inclusive. Finally, the sequence object is asked to replace\n the slice with the items of the assigned sequence. The length of\n the slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print x\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
'atom-identifiers': 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 in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name. For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``. This transformation is independent of\nthe syntactical context in which the identifier is used. If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen. If the class name\nconsists only of underscores, no transformation is done.\n',
'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``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control 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\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\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\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup 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 the\nclass dictionary of another new-style class, known as the *owner*\nclass. In the examples below, "the attribute" refers to the attribute\nwhose name is the key of the property in the owner class\'\n``__dict__``. Descriptors can only be implemented as new-style\nclasses themselves.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to 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\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of 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 defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n 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 instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\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``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control 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\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\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\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup 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\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to 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\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the 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__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of 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 defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n 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 instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n 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\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
'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\narguments. The arguments must either both be numbers, or one argument\nmust be an integer (plain or long) and the other must be a sequence.\nIn the former case, the numbers are converted to a common type and\nthen multiplied 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\n``4*0.7 + 0.34``.) The modulo operator always yields a result with\nthe same sign as its second operand (or zero); the absolute value of\nthe result is strictly smaller than the absolute value of the second\noperand [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\narguments. The numeric arguments are first converted to a common\ntype.\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``.\n',
- 'bltin-file-objects': u'\nFile Objects\n************\n\nFile objects are implemented using C\'s ``stdio`` package and can be\ncreated with the built-in ``open()`` function. File objects are also\nreturned by some other built-in functions and methods, such as\n``os.popen()`` and ``os.fdopen()`` and the ``makefile()`` method of\nsocket objects. Temporary files can be created using the ``tempfile``\nmodule, and high-level file operations such as copying, moving, and\ndeleting files and directories can be achieved with the ``shutil``\nmodule.\n\nWhen a file operation fails for an I/O-related reason, the exception\n``IOError`` is raised. This includes situations where the operation\nis not defined for some reason, like ``seek()`` on a tty device or\nwriting a file opened for reading.\n\nFiles have the following methods:\n\nfile.close()\n\n Close the file. A closed file cannot be read or written any more.\n Any operation which requires that the file be open will raise a\n ``ValueError`` after the file has been closed. Calling ``close()``\n more than once is allowed.\n\n As of Python 2.5, you can avoid having to call this method\n explicitly if you use the ``with`` statement. For example, the\n following code will automatically close *f* when the ``with`` block\n is exited:\n\n from __future__ import with_statement # This isn\'t required in Python 2.6\n\n with open("hello.txt") as f:\n for line in f:\n print line\n\n In older versions of Python, you would have needed to do this to\n get the same effect:\n\n f = open("hello.txt")\n try:\n for line in f:\n print line\n finally:\n f.close()\n\n Note: Not all "file-like" types in Python support use as a context\n manager for the ``with`` statement. If your code is intended to\n work with any file-like object, you can use the function\n ``contextlib.closing()`` instead of using the object directly.\n\nfile.flush()\n\n Flush the internal buffer, like ``stdio``\'s ``fflush()``. This may\n be a no-op on some file-like objects.\n\n Note: ``flush()`` does not necessarily write the file\'s data to disk.\n Use ``flush()`` followed by ``os.fsync()`` to ensure this\n behavior.\n\nfile.fileno()\n\n Return the integer "file descriptor" that is used by the underlying\n implementation to request I/O operations from the operating system.\n This can be useful for other, lower level interfaces that use file\n descriptors, such as the ``fcntl`` module or ``os.read()`` and\n friends.\n\n Note: File-like objects which do not have a real file descriptor should\n *not* provide this method!\n\nfile.isatty()\n\n Return ``True`` if the file is connected to a tty(-like) device,\n else ``False``.\n\n Note: If a file-like object is not associated with a real file, this\n method should *not* be implemented.\n\nfile.next()\n\n A file object is its own iterator, for example ``iter(f)`` returns\n *f* (unless *f* is closed). When a file is used as an iterator,\n typically in a ``for`` loop (for example, ``for line in f: print\n line``), the ``next()`` method is called repeatedly. This method\n returns the next input line, or raises ``StopIteration`` when EOF\n is hit when the file is open for reading (behavior is undefined\n when the file is open for writing). In order to make a ``for``\n loop the most efficient way of looping over the lines of a file (a\n very common operation), the ``next()`` method uses a hidden read-\n ahead buffer. As a consequence of using a read-ahead buffer,\n combining ``next()`` with other file methods (like ``readline()``)\n does not work right. However, using ``seek()`` to reposition the\n file to an absolute position will flush the read-ahead buffer.\n\n New in version 2.3.\n\nfile.read([size])\n\n Read at most *size* bytes from the file (less if the read hits EOF\n before obtaining *size* bytes). If the *size* argument is negative\n or omitted, read all data until EOF is reached. The bytes are\n returned as a string object. An empty string is returned when EOF\n is encountered immediately. (For certain files, like ttys, it\n makes sense to continue reading after an EOF is hit.) Note that\n this method may call the underlying C function ``fread()`` more\n than once in an effort to acquire as close to *size* bytes as\n possible. Also note that when in non-blocking mode, less data than\n was requested may be returned, even if no *size* parameter was\n given.\n\n Note: This function is simply a wrapper for the underlying ``fread()``\n C function, and will behave the same in corner cases, such as\n whether the EOF value is cached.\n\nfile.readline([size])\n\n Read one entire line from the file. A trailing newline character\n is kept in the string (but may be absent when a file ends with an\n incomplete line). [5] If the *size* argument is present and non-\n negative, it is a maximum byte count (including the trailing\n newline) and an incomplete line may be returned. An empty string is\n returned *only* when EOF is encountered immediately.\n\n Note: Unlike ``stdio``\'s ``fgets()``, the returned string contains null\n characters (``\'\\0\'``) if they occurred in the input.\n\nfile.readlines([sizehint])\n\n Read until EOF using ``readline()`` and return a list containing\n the lines thus read. If the optional *sizehint* argument is\n present, instead of reading up to EOF, whole lines totalling\n approximately *sizehint* bytes (possibly after rounding up to an\n internal buffer size) are read. Objects implementing a file-like\n interface may choose to ignore *sizehint* if it cannot be\n implemented, or cannot be implemented efficiently.\n\nfile.xreadlines()\n\n This method returns the same thing as ``iter(f)``.\n\n New in version 2.1.\n\n Deprecated since version 2.3: Use ``for line in file`` instead.\n\nfile.seek(offset[, whence])\n\n Set the file\'s current position, like ``stdio``\'s ``fseek()``. The\n *whence* argument is optional and defaults to ``os.SEEK_SET`` or\n ``0`` (absolute file positioning); other values are ``os.SEEK_CUR``\n or ``1`` (seek relative to the current position) and\n ``os.SEEK_END`` or ``2`` (seek relative to the file\'s end). There\n is no return value.\n\n For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by\n two and ``f.seek(-3, os.SEEK_END)`` sets the position to the third\n to last.\n\n Note that if the file is opened for appending (mode ``\'a\'`` or\n ``\'a+\'``), any ``seek()`` operations will be undone at the next\n write. If the file is only opened for writing in append mode (mode\n ``\'a\'``), this method is essentially a no-op, but it remains useful\n for files opened in append mode with reading enabled (mode\n ``\'a+\'``). If the file is opened in text mode (without ``\'b\'``),\n only offsets returned by ``tell()`` are legal. Use of other\n offsets causes undefined behavior.\n\n Note that not all file objects are seekable.\n\n Changed in version 2.6: Passing float values as offset has been\n deprecated.\n\nfile.tell()\n\n Return the file\'s current position, like ``stdio``\'s ``ftell()``.\n\n Note: On Windows, ``tell()`` can return illegal values (after an\n ``fgets()``) when reading files with Unix-style line-endings. Use\n binary mode (``\'rb\'``) to circumvent this problem.\n\nfile.truncate([size])\n\n Truncate the file\'s size. If the optional *size* argument is\n present, the file is truncated to (at most) that size. The size\n defaults to the current position. The current file position is not\n changed. Note that if a specified size exceeds the file\'s current\n size, the result is platform-dependent: possibilities include that\n the file may remain unchanged, increase to the specified size as if\n zero-filled, or increase to the specified size with undefined new\n content. Availability: Windows, many Unix variants.\n\nfile.write(str)\n\n Write a string to the file. There is no return value. Due to\n buffering, the string may not actually show up in the file until\n the ``flush()`` or ``close()`` method is called.\n\nfile.writelines(sequence)\n\n Write a sequence of strings to the file. The sequence can be any\n iterable object producing strings, typically a list of strings.\n There is no return value. (The name is intended to match\n ``readlines()``; ``writelines()`` does not add line separators.)\n\nFiles support the iterator protocol. Each iteration returns the same\nresult as ``file.readline()``, and iteration ends when the\n``readline()`` method returns an empty string.\n\nFile objects also offer a number of other interesting attributes.\nThese are not required for file-like objects, but should be\nimplemented if they make sense for the particular object.\n\nfile.closed\n\n bool indicating the current state of the file object. This is a\n read-only attribute; the ``close()`` method changes the value. It\n may not be available on all file-like objects.\n\nfile.encoding\n\n The encoding that this file uses. When Unicode strings are written\n to a file, they will be converted to byte strings using this\n encoding. In addition, when the file is connected to a terminal,\n the attribute gives the encoding that the terminal is likely to use\n (that information might be incorrect if the user has misconfigured\n the terminal). The attribute is read-only and may not be present\n on all file-like objects. It may also be ``None``, in which case\n the file uses the system default encoding for converting Unicode\n strings.\n\n New in version 2.3.\n\nfile.errors\n\n The Unicode error handler used along with the encoding.\n\n New in version 2.6.\n\nfile.mode\n\n The I/O mode for the file. If the file was created using the\n ``open()`` built-in function, this will be the value of the *mode*\n parameter. This is a read-only attribute and may not be present on\n all file-like objects.\n\nfile.name\n\n If the file object was created using ``open()``, the name of the\n file. Otherwise, some string that indicates the source of the file\n object, of the form ``<...>``. This is a read-only attribute and\n may not be present on all file-like objects.\n\nfile.newlines\n\n If Python was built with the *--with-universal-newlines* option to\n **configure** (the default) this read-only attribute exists, and\n for files opened in universal newline read mode it keeps track of\n the types of newlines encountered while reading the file. The\n values it can take are ``\'\\r\'``, ``\'\\n\'``, ``\'\\r\\n\'``, ``None``\n (unknown, no newlines read yet) or a tuple containing all the\n newline types seen, to indicate that multiple newline conventions\n were encountered. For files not opened in universal newline read\n mode the value of this attribute will be ``None``.\n\nfile.softspace\n\n Boolean that indicates whether a space character needs to be\n printed before another value when using the ``print`` statement.\n Classes that are trying to simulate a file object should also have\n a writable ``softspace`` attribute, which should be initialized to\n zero. This will be automatic for most classes implemented in\n Python (care may be needed for objects that override attribute\n access); types implemented in C will have to provide a writable\n ``softspace`` attribute.\n\n Note: This attribute is not used to control the ``print`` statement,\n but to allow the implementation of ``print`` to keep track of its\n internal state.\n',
+ 'bltin-file-objects': u'\nFile Objects\n************\n\nFile objects are implemented using C\'s ``stdio`` package and can be\ncreated with the built-in ``open()`` function. File objects are also\nreturned by some other built-in functions and methods, such as\n``os.popen()`` and ``os.fdopen()`` and the ``makefile()`` method of\nsocket objects. Temporary files can be created using the ``tempfile``\nmodule, and high-level file operations such as copying, moving, and\ndeleting files and directories can be achieved with the ``shutil``\nmodule.\n\nWhen a file operation fails for an I/O-related reason, the exception\n``IOError`` is raised. This includes situations where the operation\nis not defined for some reason, like ``seek()`` on a tty device or\nwriting a file opened for reading.\n\nFiles have the following methods:\n\nfile.close()\n\n Close the file. A closed file cannot be read or written any more.\n Any operation which requires that the file be open will raise a\n ``ValueError`` after the file has been closed. Calling ``close()``\n more than once is allowed.\n\n As of Python 2.5, you can avoid having to call this method\n explicitly if you use the ``with`` statement. For example, the\n following code will automatically close *f* when the ``with`` block\n is exited:\n\n from __future__ import with_statement # This isn\'t required in Python 2.6\n\n with open("hello.txt") as f:\n for line in f:\n print line\n\n In older versions of Python, you would have needed to do this to\n get the same effect:\n\n f = open("hello.txt")\n try:\n for line in f:\n print line\n finally:\n f.close()\n\n Note: Not all "file-like" types in Python support use as a context\n manager for the ``with`` statement. If your code is intended to\n work with any file-like object, you can use the function\n ``contextlib.closing()`` instead of using the object directly.\n\nfile.flush()\n\n Flush the internal buffer, like ``stdio``\'s ``fflush()``. This may\n be a no-op on some file-like objects.\n\n Note: ``flush()`` does not necessarily write the file\'s data to disk.\n Use ``flush()`` followed by ``os.fsync()`` to ensure this\n behavior.\n\nfile.fileno()\n\n Return the integer "file descriptor" that is used by the underlying\n implementation to request I/O operations from the operating system.\n This can be useful for other, lower level interfaces that use file\n descriptors, such as the ``fcntl`` module or ``os.read()`` and\n friends.\n\n Note: File-like objects which do not have a real file descriptor should\n *not* provide this method!\n\nfile.isatty()\n\n Return ``True`` if the file is connected to a tty(-like) device,\n else ``False``.\n\n Note: If a file-like object is not associated with a real file, this\n method should *not* be implemented.\n\nfile.next()\n\n A file object is its own iterator, for example ``iter(f)`` returns\n *f* (unless *f* is closed). When a file is used as an iterator,\n typically in a ``for`` loop (for example, ``for line in f: print\n line``), the ``next()`` method is called repeatedly. This method\n returns the next input line, or raises ``StopIteration`` when EOF\n is hit when the file is open for reading (behavior is undefined\n when the file is open for writing). In order to make a ``for``\n loop the most efficient way of looping over the lines of a file (a\n very common operation), the ``next()`` method uses a hidden read-\n ahead buffer. As a consequence of using a read-ahead buffer,\n combining ``next()`` with other file methods (like ``readline()``)\n does not work right. However, using ``seek()`` to reposition the\n file to an absolute position will flush the read-ahead buffer.\n\n New in version 2.3.\n\nfile.read([size])\n\n Read at most *size* bytes from the file (less if the read hits EOF\n before obtaining *size* bytes). If the *size* argument is negative\n or omitted, read all data until EOF is reached. The bytes are\n returned as a string object. An empty string is returned when EOF\n is encountered immediately. (For certain files, like ttys, it\n makes sense to continue reading after an EOF is hit.) Note that\n this method may call the underlying C function ``fread()`` more\n than once in an effort to acquire as close to *size* bytes as\n possible. Also note that when in non-blocking mode, less data than\n was requested may be returned, even if no *size* parameter was\n given.\n\n Note: This function is simply a wrapper for the underlying ``fread()``\n C function, and will behave the same in corner cases, such as\n whether the EOF value is cached.\n\nfile.readline([size])\n\n Read one entire line from the file. A trailing newline character\n is kept in the string (but may be absent when a file ends with an\n incomplete line). [5] If the *size* argument is present and non-\n negative, it is a maximum byte count (including the trailing\n newline) and an incomplete line may be returned. When *size* is not\n 0, an empty string is returned *only* when EOF is encountered\n immediately.\n\n Note: Unlike ``stdio``\'s ``fgets()``, the returned string contains null\n characters (``\'\\0\'``) if they occurred in the input.\n\nfile.readlines([sizehint])\n\n Read until EOF using ``readline()`` and return a list containing\n the lines thus read. If the optional *sizehint* argument is\n present, instead of reading up to EOF, whole lines totalling\n approximately *sizehint* bytes (possibly after rounding up to an\n internal buffer size) are read. Objects implementing a file-like\n interface may choose to ignore *sizehint* if it cannot be\n implemented, or cannot be implemented efficiently.\n\nfile.xreadlines()\n\n This method returns the same thing as ``iter(f)``.\n\n New in version 2.1.\n\n Deprecated since version 2.3: Use ``for line in file`` instead.\n\nfile.seek(offset[, whence])\n\n Set the file\'s current position, like ``stdio``\'s ``fseek()``. The\n *whence* argument is optional and defaults to ``os.SEEK_SET`` or\n ``0`` (absolute file positioning); other values are ``os.SEEK_CUR``\n or ``1`` (seek relative to the current position) and\n ``os.SEEK_END`` or ``2`` (seek relative to the file\'s end). There\n is no return value.\n\n For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by\n two and ``f.seek(-3, os.SEEK_END)`` sets the position to the third\n to last.\n\n Note that if the file is opened for appending (mode ``\'a\'`` or\n ``\'a+\'``), any ``seek()`` operations will be undone at the next\n write. If the file is only opened for writing in append mode (mode\n ``\'a\'``), this method is essentially a no-op, but it remains useful\n for files opened in append mode with reading enabled (mode\n ``\'a+\'``). If the file is opened in text mode (without ``\'b\'``),\n only offsets returned by ``tell()`` are legal. Use of other\n offsets causes undefined behavior.\n\n Note that not all file objects are seekable.\n\n Changed in version 2.6: Passing float values as offset has been\n deprecated.\n\nfile.tell()\n\n Return the file\'s current position, like ``stdio``\'s ``ftell()``.\n\n Note: On Windows, ``tell()`` can return illegal values (after an\n ``fgets()``) when reading files with Unix-style line-endings. Use\n binary mode (``\'rb\'``) to circumvent this problem.\n\nfile.truncate([size])\n\n Truncate the file\'s size. If the optional *size* argument is\n present, the file is truncated to (at most) that size. The size\n defaults to the current position. The current file position is not\n changed. Note that if a specified size exceeds the file\'s current\n size, the result is platform-dependent: possibilities include that\n the file may remain unchanged, increase to the specified size as if\n zero-filled, or increase to the specified size with undefined new\n content. Availability: Windows, many Unix variants.\n\nfile.write(str)\n\n Write a string to the file. There is no return value. Due to\n buffering, the string may not actually show up in the file until\n the ``flush()`` or ``close()`` method is called.\n\nfile.writelines(sequence)\n\n Write a sequence of strings to the file. The sequence can be any\n iterable object producing strings, typically a list of strings.\n There is no return value. (The name is intended to match\n ``readlines()``; ``writelines()`` does not add line separators.)\n\nFiles support the iterator protocol. Each iteration returns the same\nresult as ``file.readline()``, and iteration ends when the\n``readline()`` method returns an empty string.\n\nFile objects also offer a number of other interesting attributes.\nThese are not required for file-like objects, but should be\nimplemented if they make sense for the particular object.\n\nfile.closed\n\n bool indicating the current state of the file object. This is a\n read-only attribute; the ``close()`` method changes the value. It\n may not be available on all file-like objects.\n\nfile.encoding\n\n The encoding that this file uses. When Unicode strings are written\n to a file, they will be converted to byte strings using this\n encoding. In addition, when the file is connected to a terminal,\n the attribute gives the encoding that the terminal is likely to use\n (that information might be incorrect if the user has misconfigured\n the terminal). The attribute is read-only and may not be present\n on all file-like objects. It may also be ``None``, in which case\n the file uses the system default encoding for converting Unicode\n strings.\n\n New in version 2.3.\n\nfile.errors\n\n The Unicode error handler used along with the encoding.\n\n New in version 2.6.\n\nfile.mode\n\n The I/O mode for the file. If the file was created using the\n ``open()`` built-in function, this will be the value of the *mode*\n parameter. This is a read-only attribute and may not be present on\n all file-like objects.\n\nfile.name\n\n If the file object was created using ``open()``, the name of the\n file. Otherwise, some string that indicates the source of the file\n object, of the form ``<...>``. This is a read-only attribute and\n may not be present on all file-like objects.\n\nfile.newlines\n\n If Python was built with universal newlines enabled (the default)\n this read-only attribute exists, and for files opened in universal\n newline read mode it keeps track of the types of newlines\n encountered while reading the file. The values it can take are\n ``\'\\r\'``, ``\'\\n\'``, ``\'\\r\\n\'``, ``None`` (unknown, no newlines read\n yet) or a tuple containing all the newline types seen, to indicate\n that multiple newline conventions were encountered. For files not\n opened in universal newline read mode the value of this attribute\n will be ``None``.\n\nfile.softspace\n\n Boolean that indicates whether a space character needs to be\n printed before another value when using the ``print`` statement.\n Classes that are trying to simulate a file object should also have\n a writable ``softspace`` attribute, which should be initialized to\n zero. This will be automatic for most classes implemented in\n Python (care may be needed for objects that override attribute\n access); types implemented in C will have to provide a writable\n ``softspace`` attribute.\n\n Note: This attribute is not used to control the ``print`` statement,\n but to allow the implementation of ``print`` to keep track of its\n internal state.\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\nchange this.)\n\nThe operator ``not`` yields ``True`` if its argument is false,\n``False`` otherwise.\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\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\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\ninvent a value anyway, it does not bother to return a value of the\nsame type as its argument, so e.g., ``not \'foo\'`` yields ``False``,\nnot ``\'\'``.)\n',
@@ -20,39 +20,39 @@
'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``.\nBoth class 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 only if there\n is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n exception or the execution of a ``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n body is transformed into the function\'s ``__doc__`` attribute and\n therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s ``__doc__`` item and\n therefore the class\'s *docstring*.\n',
'coercion-rules': u"\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.0, 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\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator '``+``', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place 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\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n 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 called\n before that type's ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n 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\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the 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 operator is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence 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\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\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\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe forms ``<>`` and ``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where ``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>`` spelling is considered obsolescent.\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are converted to a common type. Otherwise,\nobjects of different types *always* compare unequal, and are ordered\nconsistently but arbitrarily. You can control comparison behavior of\nobjects of non-built-in types by defining a ``__cmp__`` method or rich\ncomparison methods like ``__gt__``, described in section *Special\nmethod 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 equivalents\n (the result of the built-in function ``ord()``) of their characters.\n Unicode and 8-bit strings are fully interoperable in this behavior.\n [4]\n\n* Tuples and lists are compared lexicographically using comparison of\n corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, ``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 are\n the same object; the choice whether one object is considered smaller\n or larger than another one is made arbitrarily but consistently\n within one execution of a program.\n\nThe operators ``in`` and ``not in`` test for collection membership.\n``x in s`` evaluates to true if *x* is a member of the collection *s*,\nand false otherwise. ``x not in s`` returns the negation of ``x in\ns``. The collection membership test has traditionally been bound to\nsequences; an object is a member of a collection if the collection is\na sequence and contains an element equal to that object. However, it\nmake sense for many other object types to support membership tests\nwithout being a sequence. In particular, dictionaries (for keys) and\nsets support membership 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\n*x* is 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\nbe a substring of any other string, so ``"" in "abc"`` will return\n``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,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``. If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception. (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object. ``x is\nnot y`` yields the inverse truth value. [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\ncontrol flow constructs. ``try`` specifies exception handlers and/or\ncleanup code for a group of statements. Function and class\ndefinitions are also 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\na ``DEDENT``. Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments, 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``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\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 loop\n (this can only occur for mutable sequences, i.e. lists). An internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n current item which has already been treated). Likewise, if the\n suite inserts an item in the sequence before the current item, the\n current item will be treated again the next time through the loop.\n This can lead to nasty bugs that can be avoided by making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n for x in a[:]:\n if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try" ":" suite\n ("except" [expression [("as" | ",") target]] ":" suite)+\n ["else" ":" suite]\n ["finally" ":" suite]\n try2_stmt ::= "try" ":" suite\n "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n``try``...``except``...``finally`` did not work. ``try``...``except``\nhad to be nested in ``try``...``finally``.\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object, a tuple containing an item compatible with the\nexception, or, in the (deprecated) case of string exceptions, is the\nraised string itself (note that the object identities must match, i.e.\nit must be the same string object, not just a string with the same\nvalue).\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified 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\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost. The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\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\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n 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 that same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form. The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements.\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``.\nBoth class 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 only if there\n is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n exception or the execution of a ``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n body is transformed into the function\'s ``__doc__`` attribute and\n therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s ``__doc__`` item and\n therefore the class\'s *docstring*.\n',
+ 'compound': 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\ncontrol flow constructs. ``try`` specifies exception handlers and/or\ncleanup code for a group of statements. Function and class\ndefinitions are also 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\na ``DEDENT``. Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments, 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``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\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 loop\n (this can only occur for mutable sequences, i.e. lists). An internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n current item which has already been treated). Likewise, if the\n suite inserts an item in the sequence before the current item, the\n current item will be treated again the next time through the loop.\n This can lead to nasty bugs that can be avoided by making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n for x in a[:]:\n if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try" ":" suite\n ("except" [expression [("as" | ",") target]] ":" suite)+\n ["else" ":" suite]\n ["finally" ":" suite]\n try2_stmt ::= "try" ":" suite\n "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n``try``...``except``...``finally`` did not work. ``try``...``except``\nhad to be nested in ``try``...``finally``.\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object, a tuple containing an item compatible with the\nexception, or, in the (deprecated) case of string exceptions, is the\nraised string itself (note that the object identities must match, i.e.\nit must be the same string object, not just a string with the same\nvalue).\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified 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\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost. The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\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\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the **with_item**)\n is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n 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 that same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form. The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements.\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``.\nBoth class 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 only if there\n is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n exception or the execution of a ``return``, ``continue``, or\n ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n body is transformed into the function\'s ``__doc__`` attribute and\n therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s ``__doc__`` item and\n therefore the class\'s *docstring*.\n',
'context-managers': 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\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n',
'continue': u'\nThe ``continue`` statement\n**************************\n\n continue_stmt ::= "continue"\n\n``continue`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition or\n``finally`` clause within that loop. It continues with the next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nstarting the next loop cycle.\n',
'conversions': 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 other\n 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\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances 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\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__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\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__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``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison 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\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so 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\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs. It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame. It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible --- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source. The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n >>> import pdb\n >>> import mymodule\n >>> pdb.run(\'mymodule.test()\')\n > <string>(0)?()\n (Pdb) continue\n > <string>(1)?()\n (Pdb) continue\n NameError: \'spam\'\n > <string>(1)?()\n (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n 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\n explained below). The optional *globals* and *locals* arguments\n specify the environment in which the code is executed; by default\n the dictionary of the module ``__main__`` is used. (See the\n explanation of the ``exec`` statement or the ``eval()`` built-in\n 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\ninstantiating the ``Pdb`` class and calling the method of the same\nname. If you want to access further features, you have to do this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None)\n\n ``Pdb`` is the debugger class.\n\n The *completekey*, *stdin* and *stdout* arguments are passed to the\n underlying ``cmd.Cmd`` class; see the description there.\n\n The *skip* argument, if given, must be an iterable of glob-style\n module name patterns. The debugger will not step into frames that\n originate in a module that matches one of these patterns. [1]\n\n Example call to enable tracing with *skip*:\n\n import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version 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',
+ 'debugger': u'\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs. It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame. It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible --- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source. The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n >>> import pdb\n >>> import mymodule\n >>> pdb.run(\'mymodule.test()\')\n > <string>(0)?()\n (Pdb) continue\n > <string>(1)?()\n (Pdb) continue\n NameError: \'spam\'\n > <string>(1)?()\n (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n 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\n explained below). The optional *globals* and *locals* arguments\n specify the environment in which the code is executed; by default\n the dictionary of the module ``__main__`` is used. (See the\n explanation of the ``exec`` statement or the ``eval()`` built-in\n 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\ninstantiating the ``Pdb`` class and calling the method of the same\nname. If you want to access further features, you have to do this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None)\n\n ``Pdb`` is the debugger class.\n\n The *completekey*, *stdin* and *stdout* arguments are passed to the\n underlying ``cmd.Cmd`` class; see the description there.\n\n The *skip* argument, if given, must be an iterable of glob-style\n module name patterns. The debugger will not step into frames that\n originate in a module that matches one of these patterns. [1]\n\n Example call to enable tracing with *skip*:\n\n import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version 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 that spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a ``global``\nstatement in the same code block. If the name is unbound, a\n``NameError`` exception will be raised.\n\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',
'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\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, 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\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\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 these\n operations is not available at the time the module is 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 string, an open file object, or\na code object. If it is a string, the string is parsed as a suite of\nPython statements which is then executed (unless a syntax error\noccurs). [1] If it is an open file, the file is parsed until EOF and\nexecuted. If it is a code object, it is simply executed. In all\ncases, the code that\'s executed is expected to be valid as file input\n(see section *File input*). Be aware that the ``return`` and\n``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.\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\n``__builtin__`` under the key ``__builtins__`` (!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is supported\nby the built-in function ``eval()``. The built-in functions\n``globals()`` and ``locals()`` return the current global and local\ndictionary, respectively, which may be useful to pass around for use\nby ``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 newline 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``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``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\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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\nfirst. If the name is not found there, the builtins namespace is\nsearched. The 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\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``__builtin__`` (note: no \'s\'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``__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 in\nthe same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\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\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\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 these\n operations is not available at the time the module is compiled.\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``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``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\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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\nfirst. If the name is not found there, the builtins namespace is\nsearched. The 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\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``__builtin__`` (note: no \'s\'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``__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\noperation in the same block. If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\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\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\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 these\n operations is not available at the time the module is 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\n``77e10``. The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n 3.14 10. .001 1e100 3.14e-10 0e0\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator ``-`` and the\nliteral ``1``.\n',
'for': u'\nThe ``for`` statement\n*********************\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments, 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``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\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 loop\n (this can only occur for mutable sequences, i.e. lists). An internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n 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\nis preceded by a colon ``\':\'``. These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword. If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument. If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nChanged in version 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\n``__format__()`` method of the value itself. However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting. By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\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-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n fill ::= <a character other than \'}\'>\n align ::= "<" | ">" | "=" | "^"\n sign ::= "+" | "-" | " "\n width ::= integer\n precision ::= integer\n type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'}\' (which\nsignifies the end of the field). The presence of a fill character is\nsignaled by the *next* character, which must be one of the alignment\noptions. If the second character of *format_spec* is not a valid\nalignment option, then it is assumed that both the fill character and\nthe alignment option are absent.\n\nThe meaning of the various alignment options is as follows:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'<\'`` | Forces the field to be left-aligned within the available |\n | | space (this is the default). |\n +-----------+------------------------------------------------------------+\n | ``\'>\'`` | Forces the field to be right-aligned within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n | ``\'=\'`` | Forces the padding to be placed after the sign (if any) |\n | | but before the digits. This is used for printing fields |\n | | in the form \'+000000120\'. This alignment option is only |\n | | valid for numeric types. |\n +-----------+------------------------------------------------------------+\n | ``\'^\'`` | Forces the field to be centered within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'+\'`` | indicates that a sign should be used for both positive as |\n | | well as negative numbers. |\n +-----------+------------------------------------------------------------+\n | ``\'-\'`` | indicates that a sign should be used only for negative |\n | | numbers (this is the default behavior). |\n +-----------+------------------------------------------------------------+\n | space | indicates that a leading space should be used on positive |\n | | numbers, and a minus sign on negative numbers. |\n +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output. If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 2.7: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width. If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding. This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'s\'`` | String format. This is the default type for strings and |\n | | may be omitted. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'s\'``. |\n +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'b\'`` | Binary format. Outputs the number in base 2. |\n +-----------+------------------------------------------------------------+\n | ``\'c\'`` | Character. Converts the integer to the corresponding |\n | | unicode character before printing. |\n +-----------+------------------------------------------------------------+\n | ``\'d\'`` | Decimal Integer. Outputs the number in base 10. |\n +-----------+------------------------------------------------------------+\n | ``\'o\'`` | Octal format. Outputs the number in base 8. |\n +-----------+------------------------------------------------------------+\n | ``\'x\'`` | Hex format. Outputs the number in base 16, using lower- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'X\'`` | Hex format. Outputs the number in base 16, using upper- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'d\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'d\'``. |\n +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'e\'`` | Exponent notation. Prints the number in scientific |\n | | notation using the letter \'e\' to indicate the exponent. |\n +-----------+------------------------------------------------------------+\n | ``\'E\'`` | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n | | case \'E\' as the separator character. |\n +-----------+------------------------------------------------------------+\n | ``\'f\'`` | Fixed point. Displays the number as a fixed-point number. |\n +-----------+------------------------------------------------------------+\n | ``\'F\'`` | Fixed point. Same as ``\'f\'``. |\n +-----------+------------------------------------------------------------+\n | ``\'g\'`` | General format. For a given precision ``p >= 1``, this |\n | | rounds the number to ``p`` significant digits and then |\n | | formats the result in either fixed-point format or in |\n | | scientific notation, depending on its magnitude. The |\n | | precise rules are as follows: suppose that the result |\n | | formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\n | | < p``, the number is formatted with presentation type |\n | | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number |\n | | is formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1``. In both cases insignificant trailing zeros are |\n | | removed from the significand, and the decimal point is |\n | | also removed if there are no remaining digits following |\n | | it. Postive and negative infinity, positive and negative |\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n | | ``-0`` and ``nan`` respectively, regardless of the |\n | | precision. A precision of ``0`` is treated as equivalent |\n | | to a precision of ``1``. |\n +-----------+------------------------------------------------------------+\n | ``\'G\'`` | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n | | if the number gets too large. The representations of |\n | | infinity and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'g\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | ``\'%\'`` | Percentage. Multiplies the number by 100 and displays in |\n | | fixed (``\'f\'``) format, followed by a percent sign. |\n +-----------+------------------------------------------------------------+\n | None | 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\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n \'a, b, c\'\n >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\') # 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\nbases:\n\n >>> # format also supports binary numbers\n >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a; oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n >>> \'{:,}\'.format(1234567890)\n \'1,234,567,890\'\n\nExpressing a percentage:\n\n >>> points = 19.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:{align}{fill}16}\'.format(text, fill=align, align=align)\n ...\n \'left<<<<<<<<<<<<\'\n \'^^^^^center^^^^^\'\n \'>>>>>>>>>>>right\'\n >>>\n >>> octets = [192, 168, 0, 1]\n >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n \'C0A80001\'\n >>> int(_, 16)\n 3232235521\n >>>\n >>> width = 5\n >>> for num in range(5,12):\n ... for base in \'dXob\':\n ... print \'{0:{width}{base}}\'.format(num, base=base, width=width),\n ... print\n ...\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 8 10 1000\n 9 9 11 1001\n 10 A 12 1010\n 11 B 13 1011\n',
+ 'formatstrings': 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\nis preceded by a colon ``\':\'``. These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword. If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument. If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nChanged in version 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\n``__format__()`` method of the value itself. However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting. By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\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-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n fill ::= <a character other than \'}\'>\n align ::= "<" | ">" | "=" | "^"\n sign ::= "+" | "-" | " "\n width ::= integer\n precision ::= integer\n type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'{\' or \'}\'. The\npresence of a fill character is signaled by the character following\nit, which must be one of the alignment options. If the second\ncharacter of *format_spec* is not a valid alignment option, then it is\nassumed that both the fill character and the alignment option are\nabsent.\n\nThe meaning of the various alignment options is as follows:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'<\'`` | Forces the field to be left-aligned within the available |\n | | space (this is the default for most objects). |\n +-----------+------------------------------------------------------------+\n | ``\'>\'`` | Forces the field to be right-aligned within the available |\n | | space (this is the default for numbers). |\n +-----------+------------------------------------------------------------+\n | ``\'=\'`` | Forces the padding to be placed after the sign (if any) |\n | | but before the digits. This is used for printing fields |\n | | in the form \'+000000120\'. This alignment option is only |\n | | valid for numeric types. |\n +-----------+------------------------------------------------------------+\n | ``\'^\'`` | Forces the field to be centered within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'+\'`` | indicates that a sign should be used for both positive as |\n | | well as negative numbers. |\n +-----------+------------------------------------------------------------+\n | ``\'-\'`` | indicates that a sign should be used only for negative |\n | | numbers (this is the default behavior). |\n +-----------+------------------------------------------------------------+\n | space | indicates that a leading space should be used on positive |\n | | numbers, and a minus sign on negative numbers. |\n +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output. If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 2.7: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width. If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding. This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'s\'`` | String format. This is the default type for strings and |\n | | may be omitted. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'s\'``. |\n +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'b\'`` | Binary format. Outputs the number in base 2. |\n +-----------+------------------------------------------------------------+\n | ``\'c\'`` | Character. Converts the integer to the corresponding |\n | | unicode character before printing. |\n +-----------+------------------------------------------------------------+\n | ``\'d\'`` | Decimal Integer. Outputs the number in base 10. |\n +-----------+------------------------------------------------------------+\n | ``\'o\'`` | Octal format. Outputs the number in base 8. |\n +-----------+------------------------------------------------------------+\n | ``\'x\'`` | Hex format. Outputs the number in base 16, using lower- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'X\'`` | Hex format. Outputs the number in base 16, using upper- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'d\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'d\'``. |\n +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'e\'`` | Exponent notation. Prints the number in scientific |\n | | notation using the letter \'e\' to indicate the exponent. |\n +-----------+------------------------------------------------------------+\n | ``\'E\'`` | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n | | case \'E\' as the separator character. |\n +-----------+------------------------------------------------------------+\n | ``\'f\'`` | Fixed point. Displays the number as a fixed-point number. |\n +-----------+------------------------------------------------------------+\n | ``\'F\'`` | Fixed point. Same as ``\'f\'``. |\n +-----------+------------------------------------------------------------+\n | ``\'g\'`` | General format. For a given precision ``p >= 1``, this |\n | | rounds the number to ``p`` significant digits and then |\n | | formats the result in either fixed-point format or in |\n | | scientific notation, depending on its magnitude. The |\n | | precise rules are as follows: suppose that the result |\n | | formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\n | | < p``, the number is formatted with presentation type |\n | | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number |\n | | is formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1``. In both cases insignificant trailing zeros are |\n | | removed from the significand, and the decimal point is |\n | | also removed if there are no remaining digits following |\n | | it. Positive and negative infinity, positive and negative |\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n | | ``-0`` and ``nan`` respectively, regardless of the |\n | | precision. A precision of ``0`` is treated as equivalent |\n | | to a precision of ``1``. |\n +-----------+------------------------------------------------------------+\n | ``\'G\'`` | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n | | if the number gets too large. The representations of |\n | | infinity and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'g\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | ``\'%\'`` | Percentage. Multiplies the number by 100 and displays in |\n | | fixed (``\'f\'``) format, followed by a percent sign. |\n +-----------+------------------------------------------------------------+\n | None | 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\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n \'a, b, c\'\n >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\') # 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\nbases:\n\n >>> # format also supports binary numbers\n >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a; oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n >>> \'{:,}\'.format(1234567890)\n \'1,234,567,890\'\n\nExpressing a percentage:\n\n >>> points = 19.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 that same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda forms,\ndescribed in section *Lambdas*. Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form. The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements.\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\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the latter two restrictions, but programs should not abuse\nthis freedom, as future implementations may enforce them or silently\nchange the meaning of the program.\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in an\n``exec`` statement does not affect the code block *containing* the\n``exec`` statement, and code contained in an ``exec`` statement is\nunaffected by ``global`` statements in the code containing the\n``exec`` statement. The same applies to the ``eval()``,\n``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\n the last evaluation; it is stored in the ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not 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);\n applications should not expect to define additional names using\n this convention. The set of names of this class defined by Python\n may be extended in future versions. See section *Special method\n names*.\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\nrecognized by the compiler as a name for the built-in object ``None``.\nAlthough it is not a keyword, you cannot assign a different object to\nit.\n\nChanged in version 2.5: Both ``as`` and ``with`` are only recognized\nwhen the ``with_statement`` future feature has been enabled. It will\nalways be enabled in Python 2.6. See section *The with statement* for\ndetails. Note that using ``as`` and ``with`` as identifiers will\nalways issue a warning, even when the ``with_statement`` future\ndirective is not in effect.\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not 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);\n applications should not expect to define additional names using\n this convention. The set of names of this class defined by Python\n may be extended in future versions. See section *Special method\n names*.\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',
+ '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\n the last evaluation; it is stored in the ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library). Current\n system names are discussed in the *Special method names* section\n and elsewhere. More will likely be defined in future versions of\n Python. *Any* use of ``__*__`` names, in any context, that does\n not follow explicitly documented use, is subject to breakage\n without warning.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n',
+ 'identifiers': 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\nrecognized by the compiler as a name for the built-in object ``None``.\nAlthough it is not a keyword, you cannot assign a different object to\nit.\n\nChanged in version 2.5: Both ``as`` and ``with`` are only recognized\nwhen the ``with_statement`` future feature has been enabled. It will\nalways be enabled in Python 2.6. See section *The with statement* for\ndetails. Note that using ``as`` and ``with`` as identifiers will\nalways issue a warning, even when the ``with_statement`` future\ndirective is not in effect.\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library). Current\n system names are discussed in the *Special method names* section\n and elsewhere. More will likely be defined in future versions of\n Python. *Any* use of ``__*__`` names, in any context, that does\n not follow explicitly documented use, is subject to breakage\n without warning.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n',
'if': 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\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and 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. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor a finder. If the path does not have a finder cached then\n``sys.path_hooks`` is searched by calling each object in the list with\na single argument of the path, returning a finder or raises\n``ImportError``. If a finder is returned then it is cached in\n``sys.path_importer_cache`` and then used for that path entry. If no\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname". If a name is not\nfound, ``ImportError`` is raised. If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope. If the\nwild card form of import --- ``import *`` --- is used in a function\nand the function contains or is a nested block with free variables,\nthe compiler 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``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n``from . import mod`` from a module in the ``pkg`` package then you\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimprt mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 2.6 are ``unicode_literals``,\n``print_function``, ``absolute_import``, ``division``, ``generators``,\n``nested_scopes`` and ``with_statement``. ``generators``,\n``with_statement``, ``nested_scopes`` are redundant in Python version\n2.6 and above because they 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\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by an ``exec`` statement or calls to the built-in\nfunctions ``compile()`` and ``execfile()`` that occur in a module\n``M`` containing a future statement will, by default, use the new\nsyntax or semantics associated with the future statement. This can,\nstarting with Python 2.2 be controlled by optional arguments to\n``compile()`` --- see 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:\n\n **PEP 236** - Back to the __future__\n The original proposal for the __future__ mechanism.\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\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and 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. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor a finder. If the path does not have a finder cached then\n``sys.path_hooks`` is searched by calling each object in the list with\na single argument of the path, returning a finder or raises\n``ImportError``. If a finder is returned then it is cached in\n``sys.path_importer_cache`` and then used for that path entry. If no\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname". If a name is not\nfound, ``ImportError`` is raised. If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module. The names given in ``__all__`` are all considered public\nand are required to exist. If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope. If the\nwild card form of import --- ``import *`` --- is used in a function\nand the function contains or is a nested block with free variables,\nthe compiler 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``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n``from . import mod`` from a module in the ``pkg`` package then you\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimport mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 2.6 are ``unicode_literals``,\n``print_function``, ``absolute_import``, ``division``, ``generators``,\n``nested_scopes`` and ``with_statement``. ``generators``,\n``with_statement``, ``nested_scopes`` are redundant in Python version\n2.6 and above because they 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\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by an ``exec`` statement or calls to the built-in\nfunctions ``compile()`` and ``execfile()`` that occur in a module\n``M`` containing a future statement will, by default, use the new\nsyntax or semantics associated with the future statement. This can,\nstarting with Python 2.2 be controlled by optional arguments to\n``compile()`` --- see 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:\n\n **PEP 236** - Back to the __future__\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\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe forms ``<>`` and ``!=`` are equivalent; for consistency with C,\n``!=`` is preferred; where ``!=`` is mentioned below ``<>`` is also\naccepted. The ``<>`` spelling is considered obsolescent.\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects. The objects need not have the same type.\nIf both are numbers, they are converted to a common type. Otherwise,\nobjects of different types *always* compare unequal, and are ordered\nconsistently but arbitrarily. You can control comparison behavior of\nobjects of non-built-in types by defining a ``__cmp__`` method or rich\ncomparison methods like ``__gt__``, described in section *Special\nmethod 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 equivalents\n (the result of the built-in function ``ord()``) of their characters.\n Unicode and 8-bit strings are fully interoperable in this behavior.\n [4]\n\n* Tuples and lists are compared lexicographically using comparison of\n corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, ``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 are\n the same object; the choice whether one object is considered smaller\n or larger than another one is made arbitrarily but consistently\n within one execution of a program.\n\nThe operators ``in`` and ``not in`` test for collection membership.\n``x in s`` evaluates to true if *x* is a member of the collection *s*,\nand false otherwise. ``x not in s`` returns the negation of ``x in\ns``. The collection membership test has traditionally been bound to\nsequences; an object is a member of a collection if the collection is\na sequence and contains an element equal to that object. However, it\nmake sense for many other object types to support membership tests\nwithout being a sequence. In particular, dictionaries (for keys) and\nsets support membership 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\n*x* is 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\nbe a substring of any other string, so ``"" in "abc"`` will return\n``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,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``. If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception. (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object. ``x is\nnot y`` yields the inverse truth value. [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\n``\'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_form ::= "lambda" [parameter_list]: expression\n old_lambda_form ::= "lambda" [parameter_list]: old_expression\n\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions. They are a shorthand to create anonymous functions; the\nexpression ``lambda arguments: expression`` yields a function object.\nThe unnamed object behaves like a function object defined with\n\n def name(arguments):\n return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda forms cannot contain\nstatements.\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_form\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\n``for`` or ``if`` clauses a block, nesting from left to right, and\nevaluating the expression to produce a list element each time the\ninnermost block is 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``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``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\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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\nfirst. If the name is not found there, the builtins namespace is\nsearched. The 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\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``__builtin__`` (note: no 's'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``__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 in\nthe same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\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\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\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``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``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\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule 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\nfirst. If the name is not found there, the builtins namespace is\nsearched. The 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\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``__builtin__`` (note: no 's'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``__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\noperation in the same block. If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\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\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, 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\nthe literal ``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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()`` (described below). Note\n that ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__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\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate 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\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is 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.\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\nthis.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries. The references are part of a container\'s value. In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied. So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior. Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed. E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n',
- 'operator-summary': u'\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding). Operators in the same box have the same precedence. Unless\nthe syntax is explicitly given, operators are binary. Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator | Description |\n+=================================================+=======================================+\n| ``lambda`` | Lambda expression |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else`` | Conditional expression |\n+-------------------------------------------------+---------------------------------------+\n| ``or`` | Boolean OR |\n+-------------------------------------------------+---------------------------------------+\n| ``and`` | Boolean AND |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x* | Boolean NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``, | Comparisons, including membership |\n| ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | tests and identity tests, |\n| ``==`` | |\n+-------------------------------------------------+---------------------------------------+\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+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``**`` | Exponentiation [8] |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``, | Subscription, slicing, call, |\n| ``x(arguments...)``, ``x.attribute`` | attribute reference |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``, | Binding or tuple display, list |\n| ``{key:datum...}``, ```expressions...``` | display, dictionary display, string |\n| | conversion |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension "leaks" the\n control variables of each ``for`` it contains into the containing\n scope. However, this behavior is deprecated, and relying on it\n will not work in Python 3.0\n\n[2] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n may not be true numerically due to roundoff. For example, and\n assuming a platform on which a Python float is an IEEE 754 double-\n precision number, in order that ``-1e-100 % 1e100`` have the same\n sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n which is numerically exactly equal to ``1e100``. Function\n ``fmod()`` in the ``math`` module returns a result whose sign\n matches the sign of the first argument instead, and so returns\n ``-1e-100`` in this case. Which approach is more appropriate\n depends on the application.\n\n[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``\n due to rounding. In such cases, Python returns the latter result,\n in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n close to ``x``.\n\n[4] While comparisons between unicode strings make sense at the byte\n level, they may be counter-intuitive to users. For example, the\n 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 constructing\n lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of the\n 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 dynamic\n nature of descriptors, you may notice seemingly unusual behaviour\n in certain uses of the ``is`` operator, like those involving\n comparisons between instance methods, or constants. Check their\n documentation for more info.\n\n[8] The power operator ``**`` binds less tightly than an arithmetic or\n bitwise unary operator on its right, that is, ``2**-1`` is\n ``0.5``.\n',
+ '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\nthis.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries. The references are part of a container\'s value. In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied. So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior. Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed. E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n',
+ 'operator-summary': u'\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding). Operators in the same box have the same precedence. Unless\nthe syntax is explicitly given, operators are binary. Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator | Description |\n+=================================================+=======================================+\n| ``lambda`` | Lambda expression |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else`` | Conditional expression |\n+-------------------------------------------------+---------------------------------------+\n| ``or`` | Boolean OR |\n+-------------------------------------------------+---------------------------------------+\n| ``and`` | Boolean AND |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x* | Boolean NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``, | Comparisons, including membership |\n| ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | tests and identity tests, |\n| ``==`` | |\n+-------------------------------------------------+---------------------------------------+\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...]``, | Binding or tuple display, list |\n| ``{key:datum...}``, ```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" the\n control variables of each ``for`` it contains into the containing\n scope. However, this behavior is deprecated, and relying on it\n will not work in Python 3.0\n\n[2] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n may not be true numerically due to roundoff. For example, and\n assuming a platform on which a Python float is an IEEE 754 double-\n precision number, in order that ``-1e-100 % 1e100`` have the same\n sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n which is numerically exactly equal to ``1e100``. The function\n ``math.fmod()`` returns a result whose sign matches the sign of\n the first argument instead, and so returns ``-1e-100`` in this\n case. Which approach is more appropriate depends on the\n application.\n\n[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``\n due to rounding. In such cases, Python returns the latter result,\n in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n close to ``x``.\n\n[4] While comparisons between unicode strings make sense at the byte\n level, they may be counter-intuitive to users. For example, the\n 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 constructing\n lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of the\n 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 dynamic\n nature of descriptors, you may notice seemingly unusual behaviour\n in certain uses of the ``is`` operator, like those involving\n comparisons between instance methods, or constants. Check their\n documentation for more info.\n\n[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 or\n bitwise unary operator on its right, that is, ``2**-1`` is\n ``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\n2.2. In Python 2.1 and before, if both arguments were of integer types\nand the second argument was negative, an exception was raised).\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``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 built-in\n file objects often do not properly emulate this aspect of the file\n object\'s behavior, so it is best not to rely on this.\n\nA ``\'\\n\'`` character is written at the end, unless the ``print``\nstatement ends with a comma. This is the only action if the statement\ncontains just 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\n``>>`` must evaluate to a "file-like" object, specifically an object\nthat has a ``write()`` method as described above. With this extended\nform, the subsequent expressions are printed to this file object. If\nthe first expression evaluates to ``None``, then ``sys.stdout`` is\nused as the file for output.\n',
@@ -63,21 +63,21 @@
'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,\nn)``. Negative shift counts raise a ``ValueError`` exception.\n\nNote: In the current implementation, the right-hand operand is required to\n be at most ``sys.maxsize``. If the right-hand operand is larger\n than ``sys.maxsize`` an ``OverflowError`` exception is raised.\n',
'slicings': 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\nslicing:\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\nthe expressions 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()``\n to get a list of an object's attributes. This attribute is no\n longer available.\n\nobject.__members__\n\n Deprecated since version 2.2: Use the built-in function ``dir()``\n to get a list of an object's attributes. This attribute is no\n longer 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 in\n the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\n ``[1.0, 2.0]``, and similarly for tuples.\n\n[3] They must have since the parser can't tell the type of the\n operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n tuple whose only element is the tuple to be formatted.\n\n[5] The advantage of leaving the newline on is that returning an empty\n string is then an unambiguous EOF indication. It is also possible\n (in cases where it might matter, for example, if you want to make\n an exact copy of a file while scanning its lines) to tell whether\n the last line of a file ended in a newline or not (yes this\n 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\nclass, then ``x[i]`` is roughly equivalent to ``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x, i)`` for new-style\nclasses. Except where mentioned, attempts to execute an operation\nraise an exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances 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\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__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\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__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``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison 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\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so 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``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control 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\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\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\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup 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 the\nclass dictionary of another new-style class, known as the *owner*\nclass. In the examples below, "the attribute" refers to the attribute\nwhose name is the key of the property in the owner class\'\n``__dict__``. Descriptors can only be implemented as new-style\nclasses themselves.\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or ``None`` when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to 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\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of 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 defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n 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 instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n 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\nclass definition is read into a separate namespace and the value of\nclass name 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 the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\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\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n Return true if *instance* should be considered a (direct or\n indirect) instance of *class*. If defined, called to implement\n ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n Return true if *subclass* should be considered a (direct or\n indirect) subclass of *class*. If defined, called to implement\n ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass. They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base Classes\n Includes the specification for customizing ``isinstance()`` and\n ``issubclass()`` behavior through ``__instancecheck__()`` and\n ``__subclasscheck__()``, with motivation for this functionality\n in the context of adding Abstract Base Classes (see the ``abc``\n module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python\'s\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__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``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``iterkeys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``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\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\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\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n\n\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\n CPython currently still implement ``__getslice__()``. Therefore,\n you have to override it in derived classes when implementing\n slicing.)\n\n Called to implement evaluation of ``self[i:j]``. The returned\n object should be of the same type as *self*. Note that missing *i*\n or *j* in the slice expression are replaced by zero or\n ``sys.maxint``, respectively. If negative indexes are used in the\n slice, the length of the sequence is added to that index. If the\n instance does not implement the ``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is made that indexes\n adjusted this way are not still negative. Indexes which are\n greater than the length of the sequence are not modified. If no\n ``__getslice__()`` is found, a slice object is created instead, and\n 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\n for extended slicing of the form ``self[i:j:k]``, a slice object is\n created, and passed to ``__setitem__()``, instead of\n ``__setslice__()`` being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of ``self[i:j]``. Same notes for *i*\n and *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\n``__delitem__()`` is called 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\nslice objects 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\nhandling of negative indices before the ``__*slice__()`` methods are\ncalled. When negative indexes are used, the ``__*item__()`` methods\nreceive them as provided, but the ``__*slice__()`` methods get a\n"cooked" form of the index values. For each negative index value, the\nlength of the sequence is added to the index before calling the method\n(which may still result in a negative index); this is the customary\nhandling of negative indexes by the built-in sequence types, and the\n``__*item__()`` methods are expected to do this as well. However,\nsince they should already be doing that, negative indexes cannot be\npassed in; they must be constrained to the bounds of the sequence\nbefore being passed to the ``__*item__()`` methods. Calling ``max(0,\ni)`` conveniently returns the 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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()`` (described below). Note\n that ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__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\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate 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\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is 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.0, 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\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator \'``+``\', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place 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\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n 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 called\n before that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n 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\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the 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 operator is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence 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\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\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\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup 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\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\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\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n',
+ '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\nclass, then ``x[i]`` is roughly equivalent to ``x.__getitem__(i)`` for\nold-style classes and ``type(x).__getitem__(x, i)`` for new-style\nclasses. Except where mentioned, attempts to execute an operation\nraise an exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. ``__new__()`` is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of ``__new__()`` should be the new object instance (usually\n an instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s ``__new__()`` method using\n ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If ``__new__()`` returns an instance of *cls*, then the new\n instance\'s ``__init__()`` method will be invoked like\n ``__init__(self[, ...])``, where *self* is the new instance and the\n remaining arguments are the same as were passed to ``__new__()``.\n\n If ``__new__()`` does not return an instance of *cls*, then the new\n instance\'s ``__init__()`` method will not be invoked.\n\n ``__new__()`` is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called when the instance is created. The arguments are those\n passed to the class constructor expression. If a base class has an\n ``__init__()`` method, the derived class\'s ``__init__()`` method,\n if any, must explicitly call it to ensure proper initialization of\n the base class part of the instance; for example:\n ``BaseClass.__init__(self, [args...])``. As a special constraint\n on constructors, no value may be returned; doing so will cause a\n ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a ``__del__()`` method,\n the derived class\'s ``__del__()`` method, if any, must explicitly\n call it to ensure proper deletion of the base class part of the\n instance. Note that it is possible (though not recommended!) for\n the ``__del__()`` method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n ``__del__()`` methods are called for objects that still exist when\n the interpreter exits.\n\n Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n decrements the reference count for ``x`` by one, and the latter\n is only called when ``x``\'s reference count reaches zero. Some\n common situations that may prevent the reference count of an\n object from going to zero include: circular references between\n objects (e.g., a doubly-linked list or a tree data structure with\n parent and child pointers); a reference to the object on the\n stack frame of a function that caught an exception (the traceback\n stored in ``sys.exc_traceback`` keeps the stack frame alive); or\n a reference to the object on the stack frame that raised an\n unhandled exception in interactive mode (the traceback stored in\n ``sys.last_traceback`` keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing ``None`` in\n ``sys.exc_traceback`` or ``sys.last_traceback``. Circular\n references which are garbage are detected when the option cycle\n detector is enabled (it\'s on by default), but can only be cleaned\n up if there are no Python-level ``__del__()`` methods involved.\n Refer to the documentation for the ``gc`` module for more\n information about how ``__del__()`` methods are handled by the\n cycle detector, particularly the description of the ``garbage``\n value.\n\n Warning: Due to the precarious circumstances under which ``__del__()``\n methods are invoked, exceptions that occur during their execution\n are ignored, and a warning is printed to ``sys.stderr`` instead.\n Also, when ``__del__()`` is invoked in response to a module being\n deleted (e.g., when execution of the program is done), other\n globals referenced by the ``__del__()`` method may already have\n been deleted or in the process of being torn down (e.g. the\n import machinery shutting down). For this reason, ``__del__()``\n methods should do the absolute minimum needed to maintain\n external invariants. Starting with version 1.5, Python\n guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n Called by the ``repr()`` built-in function and by string\n conversions (reverse quotes) to compute the "official" string\n representation of an object. If at all possible, this should look\n like a valid Python expression that could be used to recreate an\n object with the same value (given an appropriate environment). If\n this is not possible, a string of the form ``<...some useful\n description...>`` should be returned. The return value must be a\n string object. If a class defines ``__repr__()`` but not\n ``__str__()``, then ``__repr__()`` is also used when an "informal"\n string representation of instances 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\n to be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__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\n ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and\n ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and\n ``x>=y`` calls ``x.__ge__(y)``.\n\n A rich comparison method may return the singleton\n ``NotImplemented`` if it does not implement the operation for a\n given pair of arguments. By convention, ``False`` and ``True`` are\n returned for a successful comparison. However, these methods can\n return any value, so if the comparison operator is used in a\n Boolean context (e.g., in the condition of an ``if`` statement),\n Python will call ``bool()`` on the value to determine if the result\n is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of ``x==y`` does not imply that ``x!=y`` is false.\n Accordingly, when defining ``__eq__()``, one should also define\n ``__ne__()`` so that the operators will behave as expected. See\n the paragraph on ``__hash__()`` for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n reflection, and ``__eq__()`` and ``__ne__()`` are their own\n reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see ``functools.total_ordering()``.\n\nobject.__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``.\n If no ``__cmp__()``, ``__eq__()`` or ``__ne__()`` operation is\n defined, class instances are compared by object identity\n ("address"). See also the description of ``__hash__()`` for some\n important notes on creating *hashable* objects which support custom\n comparison 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\n members of hashed collections including ``set``, ``frozenset``, and\n ``dict``. ``__hash__()`` should return an integer. The only\n required property is that objects which compare equal have the same\n hash value; it is advised to somehow mix together (e.g. using\n exclusive or) the hash values for the components of the object that\n also play a part in comparison of objects.\n\n If a class does not define a ``__cmp__()`` or ``__eq__()`` method\n it should not define a ``__hash__()`` operation either; if it\n defines ``__cmp__()`` or ``__eq__()`` but not ``__hash__()``, its\n instances will not be usable in hashed collections. If a class\n defines mutable objects and implements a ``__cmp__()`` or\n ``__eq__()`` method, it should not implement ``__hash__()``, since\n hashable collection implementations require that a object\'s hash\n value is immutable (if the object\'s hash value changes, it will be\n in the wrong hash bucket).\n\n User-defined classes have ``__cmp__()`` and ``__hash__()`` methods\n by default; with them, all objects compare unequal (except with\n themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n Classes which inherit a ``__hash__()`` method from a parent class\n but change the meaning of ``__cmp__()`` or ``__eq__()`` such that\n the hash value returned is no longer appropriate (e.g. by switching\n to a value-based concept of equality instead of the default\n identity based equality) can explicitly flag themselves as being\n unhashable by setting ``__hash__ = None`` in the class definition.\n Doing so 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``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for ``self``). ``name`` is the attribute name.\n This method should return the (computed) attribute value or raise\n an ``AttributeError`` exception.\n\n Note that if the attribute is found through the normal mechanism,\n ``__getattr__()`` is not called. (This is an intentional asymmetry\n between ``__getattr__()`` and ``__setattr__()``.) This is done both\n for efficiency reasons and because otherwise ``__getattr__()``\n would have no way to access other attributes of the instance. Note\n that at least for instance variables, you can fake total control by\n not inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n ``__getattribute__()`` method below for a way to actually get total\n control 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\n cause a recursive call to itself. Instead, it should insert the\n value in the dictionary of instance attributes, e.g.,\n ``self.__dict__[name] = value``. For new-style classes, rather\n than accessing the instance dictionary, it should call the base\n class method with the same name, for example,\n ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n Like ``__setattr__()`` but for attribute deletion instead of\n assignment. This should only be implemented if ``del obj.name`` is\n meaningful for the object.\n\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\n ``__getattr__()``, the latter will not be called unless\n ``__getattribute__()`` either calls it explicitly or raises an\n ``AttributeError``. This method should return the (computed)\n attribute value or raise an ``AttributeError`` exception. In order\n to avoid infinite recursion in this method, its implementation\n should always call the base class method with the same name to\n access any attributes it needs, for example,\n ``object.__getattribute__(self, name)``.\n\n Note: This method may still be bypassed when looking up special methods\n as the result of implicit invocation via language syntax or\n built-in functions. See *Special method lookup 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\n ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass ``object()`` or\n``type()``).\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: ``x.__get__(a)``.\n\nInstance Binding\n If binding to 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\n ``A`` immediately preceding ``B`` and then invokes the descriptor\n with the 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__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary. If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor. Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method. Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary. In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of 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 defining\n *__slots__* do not support weak references to its instances. If weak\n reference support is needed, then add ``\'__weakref__\'`` to the\n sequence of strings in the *__slots__* declaration.\n\n 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 instance\n variable defined by the base class slot is inaccessible (except by\n retrieving its descriptor directly from the base class). This\n renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as ``long``, ``str`` and\n ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n 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\nclass definition is read into a separate namespace and the value of\nclass name 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 the\n role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\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\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n Return true if *instance* should be considered a (direct or\n indirect) instance of *class*. If defined, called to implement\n ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n Return true if *subclass* should be considered a (direct or\n indirect) subclass of *class*. If defined, called to implement\n ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass. They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base Classes\n Includes the specification for customizing ``isinstance()`` and\n ``issubclass()`` behavior through ``__instancecheck__()`` and\n ``__subclasscheck__()``, with motivation for this functionality\n in the context of adding Abstract Base Classes (see the ``abc``\n module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python\'s\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__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``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``iterkeys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn\'t define a ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``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\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\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\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n\n\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\n CPython currently still implement ``__getslice__()``. Therefore,\n you have to override it in derived classes when implementing\n slicing.)\n\n Called to implement evaluation of ``self[i:j]``. The returned\n object should be of the same type as *self*. Note that missing *i*\n or *j* in the slice expression are replaced by zero or\n ``sys.maxint``, respectively. If negative indexes are used in the\n slice, the length of the sequence is added to that index. If the\n instance does not implement the ``__len__()`` method, an\n ``AttributeError`` is raised. No guarantee is made that indexes\n adjusted this way are not still negative. Indexes which are\n greater than the length of the sequence are not modified. If no\n ``__getslice__()`` is found, a slice object is created instead, and\n 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\n for extended slicing of the form ``self[i:j:k]``, a slice object is\n created, and passed to ``__setitem__()``, instead of\n ``__setslice__()`` being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of ``self[i:j]``. Same notes for *i*\n and *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\n``__delitem__()`` is called 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\nslice objects 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\nhandling of negative indices before the ``__*slice__()`` methods are\ncalled. When negative indexes are used, the ``__*item__()`` methods\nreceive them as provided, but the ``__*slice__()`` methods get a\n"cooked" form of the index values. For each negative index value, the\nlength of the sequence is added to the index before calling the method\n(which may still result in a negative index); this is the customary\nhandling of negative indexes by the built-in sequence types, and the\n``__*item__()`` methods are expected to do this as well. However,\nsince they should already be doing that, negative indexes cannot be\npassed in; they must be constrained to the bounds of the sequence\nbefore being passed to the ``__*item__()`` methods. Calling ``max(0,\ni)`` conveniently returns the 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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For\n instance, to evaluate the expression ``x + y``, where *x* is an\n instance of a class that has an ``__add__()`` method,\n ``x.__add__(y)`` is called. The ``__divmod__()`` method should be\n the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n should not be related to ``__truediv__()`` (described below). Note\n that ``__pow__()`` should be defined to accept an optional third\n argument if the ternary version of the built-in ``pow()`` function\n is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return ``NotImplemented``.\n\nobject.__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()``,\n ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with\n reflected (swapped) operands. These functions are only called if\n the left operand does not support the corresponding operation and\n the operands are of different types. [2] For instance, to evaluate\n the expression ``x - y``, where *y* is an instance of a class that\n has an ``__rsub__()`` method, ``y.__rsub__(x)`` is called if\n ``x.__sub__(y)`` returns *NotImplemented*.\n\n Note that ternary ``pow()`` will not try calling ``__rpow__()``\n (the coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left operand\'s\n type and that subclass provides the reflected method for the\n operation, this method will be called before the left operand\'s\n non-reflected method. This behavior allows subclasses to\n override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__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\n should attempt to do the operation in-place (modifying *self*) and\n return the result (which could be, but does not have to be,\n *self*). If a specific method is not defined, the augmented\n assignment falls back to the normal methods. For instance, to\n execute the statement ``x += y``, where *x* is an instance of a\n class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n called. If *x* is an instance of a class that does not define a\n ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations (``-``, ``+``,\n ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions ``complex()``,\n ``int()``, ``long()``, and ``float()``. Should return a value of\n the appropriate 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\n object to attempt a coercion (but sometimes, if the implementation\n of the other type cannot be changed, it is useful to do the\n conversion to the other type here). A return value of\n ``NotImplemented`` is 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.0, 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\n implemented at all.\n\n* Below, ``__op__()`` and ``__rop__()`` are used to signify the\n generic method names corresponding to an operator; ``__iop__()`` is\n used for the corresponding in-place operator. For example, for the\n operator \'``+``\', ``__add__()`` and ``__radd__()`` are used for the\n left and right variant of the binary operator, and ``__iadd__()``\n for the in-place 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\n ``NotImplemented``, a ``TypeError`` exception is raised. But see\n 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 called\n before that type\'s ``__op__()`` or ``__rop__()`` method is called,\n but no sooner. If the coercion returns an object of a different\n type for the operand whose coercion is invoked, part of the process\n 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\n coercion. When the operation falls back to ``__op__()`` and/or\n ``__rop__()``, the 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 operator is a sequence that implements sequence\n repetition, and the other is an integer (``int`` or ``long``),\n sequence 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\n types implement a ``__coerce__()`` method, for use by the built-in\n ``coerce()`` function.\n\n Changed in version 2.7.\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\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code. Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The ``with``\n statement will bind this method\'s return value to the target(s)\n specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be ``None``.\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that ``__exit__()`` methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n\n\nSpecial method lookup 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\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\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\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n certain controlled conditions. It generally isn\'t a good idea\n though, since it can lead to some very strange behaviour if it is\n handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as ``__add__()``) fails the operation is\n not supported, which is why the reflected method is not called.\n',
'string-conversions': u'\nString conversions\n******************\n\nA string conversion is an expression list enclosed in reverse (a.k.a.\nbackward) quotes:\n\n string_conversion ::= "\'" expression_list "\'"\n\nA string conversion evaluates the contained expression list and\nconverts the resulting object into a string according to rules\nspecific to its type.\n\nIf the object is a string, a number, ``None``, or a tuple, list or\ndictionary containing only objects whose type is one of these, the\nresulting string is a valid Python expression which can be passed to\nthe built-in function ``eval()`` to yield an expression with the same\nvalue (or an approximation, if floating point numbers are involved).\n\n(In particular, converting a string adds quotes around it and converts\n"funny" characters to escape sequences that are safe to print.)\n\nRecursive objects (for example, lists or dictionaries that contain a\nreference to themselves, directly or indirectly) use ``...`` to\nindicate a recursive reference, and the result cannot be passed to\n``eval()`` to get an equal value (``SyntaxError`` will be raised\ninstead).\n\nThe built-in function ``repr()`` performs exactly the same conversion\nin its argument as enclosing it in parentheses and reverse quotes\ndoes. The built-in function ``str()`` performs a similar but more\nuser-friendly conversion.\n',
- 'string-methods': u'\nString Methods\n**************\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\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\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n 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\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n 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. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String 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 in the string are lowercase and\n 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 in the string are uppercase and\n 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\n ``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 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*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\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\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is 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, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\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\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\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.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\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 ``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,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. 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 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. The two prefix characters may be\ncombined; in this case, ``\'u\'`` must appear before ``\'r\'``.\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 be\n 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). Individual code units which form parts of a surrogate\n pair can be encoded using this escape sequence.\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 byte\n with the given value; it is not necessary that the byte encodes a\n character in the source character set. In a Unicode literal, these\n escapes denote a Unicode character with the given 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``\'n\'``. String quotes can be escaped with a backslash, but the\nbackslash remains in the string; for example, ``r"\\""`` is a valid\nstring literal consisting of two characters: a backslash and a double\nquote; ``r"\\"`` is not a valid string literal (even a raw string\ncannot end in an odd number of backslashes). Specifically, *a raw\nstring cannot end in a single backslash* (since the backslash would\nescape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix is used in conjunction with a\n``\'u\'`` or ``\'U\'`` prefix, then the ``\\uXXXX`` and ``\\UXXXXXXXX``\nescape sequences are processed while *all other backslashes are left\nin the string*. For example, the string literal ``ur"\\u0062\\n"``\nconsists of three Unicode characters: \'LATIN SMALL LETTER B\', \'REVERSE\nSOLIDUS\', and \'LATIN SMALL LETTER N\'. Backslashes can be escaped with\na preceding backslash; however, both remain in the string. As a\nresult, ``\\uXXXX`` escape sequences are only recognized when there are\nan odd number of backslashes.\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\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n 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\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n 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. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\n Note: The ``find()`` method should be used only if you need to know the\n position of *sub*. To check if *sub* is a substring or not, use\n 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.0,\n and should be preferred to the ``%`` formatting described in\n *String 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 in the string are lowercase and\n 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 in the string are uppercase and\n 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\n ``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 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*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\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\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is 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, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\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\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\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.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\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 ``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,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. 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\nignored in Python 2; it indicates that the literal should become a\nbytes literal in Python 3 (e.g. when code is automatically converted\nwith 2to3). A ``\'u\'`` or ``\'b\'`` prefix may be followed by an ``\'r\'``\nprefix.\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 be\n 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). Individual code units which form parts of a surrogate\n pair can be encoded using this escape sequence.\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 byte\n with the given value; it is not necessary that the byte encodes a\n character in the source character set. In a Unicode literal, these\n escapes denote a Unicode character with the given 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``\'n\'``. String quotes can be escaped with a backslash, but the\nbackslash remains in the string; for example, ``r"\\""`` is a valid\nstring literal consisting of two characters: a backslash and a double\nquote; ``r"\\"`` is not a valid string literal (even a raw string\ncannot end in an odd number of backslashes). Specifically, *a raw\nstring cannot end in a single backslash* (since the backslash would\nescape the following quote character). Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n\nWhen an ``\'r\'`` or ``\'R\'`` prefix is used in conjunction with a\n``\'u\'`` or ``\'U\'`` prefix, then the ``\\uXXXX`` and ``\\UXXXXXXXX``\nescape sequences are processed while *all other backslashes are left\nin the string*. For example, the string literal ``ur"\\u0062\\n"``\nconsists of three Unicode characters: \'LATIN SMALL LETTER B\', \'REVERSE\nSOLIDUS\', and \'LATIN SMALL LETTER N\'. Backslashes can be escaped with\na preceding backslash; however, both remain in the string. As a\nresult, ``\\uXXXX`` escape sequences are only recognized when there are\nan odd number of backslashes.\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\n``x``.) The resulting value must be a nonnegative integer less than\nthe number of items in the sequence, and the subscription selects the\nitem whose index is that value (counting from zero).\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``,\n ``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\n the integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n",
'try': 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" | ",") target]] ":" 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``\nhad to be nested in ``try``...``finally``.\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object, a tuple containing an item compatible with the\nexception, or, in the (deprecated) case of string exceptions, is the\nraised string itself (note that the object identities must match, i.e.\nit must be the same string object, not just a string with the same\nvalue).\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified 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\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost. The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
- 'types': 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``.\n It is used to signify the absence of a value in many situations,\n e.g., it is returned from functions that don\'t explicitly return\n anything. Its truth value is false.\n\nNotImplemented\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``NotImplemented``. Numeric methods and rich comparison methods may\n return this value if they do not implement the operation for the\n operands provided. (The interpreter will then try the reflected\n operation, or some other fallback, depending on the operator.) Its\n truth value is true.\n\nEllipsis\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``Ellipsis``. It is used to indicate the presence of the ``...``\n syntax 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 only\n 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 is\n dwarfed by the overhead of using objects in Python, so there is\n no reason to complicate the language with two kinds of floating\n point numbers.\n\n ``numbers.Complex``\n These represent complex numbers as a pair of machine-level\n double precision floating point numbers. The same caveats apply\n as for floating point numbers. The real and imaginary parts of a\n complex number ``z`` can be retrieved through the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n These represent finite ordered sets indexed by non-negative\n numbers. The built-in function ``len()`` returns the number of\n items of a sequence. When the length of a sequence is *n*, the\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by ``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\n expression, a slice is a sequence of the same type. This implies\n that the index set is renumbered so that it starts at 0.\n\n Some sequences also support "extended slicing" with a third "step"\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n *j*.\n\n Sequences are distinguished according to their mutability:\n\n Immutable sequences\n An object of an immutable sequence type cannot change once it is\n created. (If the object contains references to other objects,\n these other objects may be mutable and may be changed; however,\n the collection of objects directly referenced by an immutable\n object cannot change.)\n\n The following types are immutable sequences:\n\n Strings\n The items of a string 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\n built-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\n a 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\n immutable and *hashable*, it can be used again as an element of\n another set, or as a dictionary key.\n\nMappings\n These represent finite sets of objects indexed by arbitrary index\n sets. The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from the mapping ``a``; this can be used in expressions and\n as the target of assignments or ``del`` statements. The built-in\n function ``len()`` returns the number of items in a mapping.\n\n There is currently a single intrinsic mapping type:\n\n Dictionaries\n These represent finite sets of objects indexed by nearly\n arbitrary values. The only types of values not acceptable as\n keys are values containing lists or dictionaries or other\n mutable types that are compared by value rather than by object\n identity, the reason being that the efficient implementation of\n dictionaries requires a key\'s hash value to remain constant.\n Numeric types used for keys obey the normal rules for numeric\n comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``) then they can be used interchangeably to index the same\n dictionary entry.\n\n Dictionaries are mutable; they can be created by the ``{...}``\n notation (see section *Dictionary displays*).\n\n The extension modules ``dbm``, ``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 | ``func_doc`` | The function\'s documentation | Writable |\n | | string, or ``None`` if | |\n | | unavailable | |\n +-------------------------+---------------------------------+-------------+\n | ``__doc__`` | Another way of spelling | Writable |\n | | ``func_doc`` | |\n +-------------------------+---------------------------------+-------------+\n | ``func_name`` | The function\'s name | Writable |\n +-------------------------+---------------------------------+-------------+\n | ``__name__`` | Another way of spelling | Writable |\n | | ``func_name`` | |\n +-------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_defaults`` | A tuple containing default | Writable |\n | | argument values for those | |\n | | arguments that have defaults, | |\n | | or ``None`` if no arguments | |\n | | have a default value | |\n +-------------------------+---------------------------------+-------------+\n | ``func_code`` | The code object representing | Writable |\n | | the compiled function body. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_globals`` | A reference to the dictionary | Read-only |\n | | that holds the function\'s | |\n | | global variables --- the global | |\n | | namespace of the module in | |\n | | which the function was defined. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_dict`` | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_closure`` | ``None`` or a tuple of cells | Read-only |\n | | that 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 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\n for 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\n the 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 3.0 forward-compatibility,\n ``im_func`` is also available as ``__func__``, and ``im_self``\n as ``__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\n unbound. When one is created by retrieving a user-defined\n function object from a class via one of its instances, its\n ``im_self`` attribute is the instance, and the method object is\n said to be bound. In either case, the new method\'s ``im_class``\n attribute is the class from which the retrieval takes place, and\n its ``im_func`` 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 (the same as the ``im_class``\n attribute), and its ``im_func`` attribute is the function object\n 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\n restriction that the first argument must be an instance of the\n proper class (``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\n a function ``f()``, and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` 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\n ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note that the transformation from function object to (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\n the end, a ``StopIteration`` exception is raised and the\n iterator will have reached the end of the set of values to be\n returned.\n\n Built-in functions\n A built-in function object is a wrapper around a C function.\n Examples of built-in functions are ``len()`` and ``math.sin()``\n (``math`` is a standard built-in module). The number and type of\n the arguments are determined by the C function. Special read-\n only attributes: ``__doc__`` is the function\'s documentation\n string, or ``None`` if unavailable; ``__name__`` is the\n function\'s name; ``__self__`` is set to ``None`` (but see the\n next item); ``__module__`` is the name of the module the\n function was defined in or ``None`` if unavailable.\n\n Built-in methods\n This is really a different disguise of a built-in function, this\n time containing an object passed to the C function as an\n implicit extra argument. An example of a built-in method is\n ``alist.append()``, assuming *alist* is a list object. In this\n case, the special read-only attribute ``__self__`` is set to the\n object denoted by *list*.\n\n 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,\n the 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 Predefined (writable) attributes: ``__name__`` is the module\'s\n name; ``__doc__`` is the module\'s documentation string, or ``None``\n if unavailable; ``__file__`` is the pathname of the file from which\n the module was loaded, if it was loaded from a file. The\n ``__file__`` attribute is not present for C modules that are\n statically linked into the interpreter; for extension modules\n loaded dynamically from a shared library, it is the pathname of the\n shared library file.\n\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\n translated to ``C.__dict__["x"]`` (although for new-style classes\n in particular there are a number of hooks which allow for other\n means of locating attributes). When the attribute name is not found\n there, the attribute search continues in the base classes. For\n old-style classes, the search is depth-first, left-to-right in the\n order of occurrence in the base class list. New-style classes use\n the more complex C3 method resolution order which behaves correctly\n even in the presence of \'diamond\' inheritance structures where\n there are multiple inheritance paths leading back to a common\n ancestor. Additional details on the C3 MRO used by new-style\n classes can be found in the documentation accompanying the 2.3\n release at http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a 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_class`` and ``im_self`` attributes are\n both ``C``. When it would yield a static method object, it is\n transformed into the object wrapped by the static method object.\n See section *Implementing Descriptors* for another way in which\n attributes retrieved from a class may differ from those actually\n contained in its ``__dict__`` (note that only new-style classes\n 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__``\n is the module name in which the class was defined; ``__dict__`` is\n the dictionary containing the class\'s namespace; ``__bases__`` is a\n tuple (possibly empty or a singleton) containing the base classes,\n in the order of their occurrence in the base class list;\n ``__doc__`` is the class\'s documentation string, or None if\n undefined.\n\nClass instances\n A class instance is created by calling a class object (see above).\n A class instance has a namespace implemented as a dictionary which\n is the first place in which attribute references are searched.\n When an attribute is not found there, and the instance\'s class has\n an attribute by that name, the search continues with the class\n attributes. If a class attribute is found that is a user-defined\n function object 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\n the 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\n instead of updating the instance dictionary directly.\n\n Class instances can pretend to be numbers, sequences, or mappings\n if they have methods with certain special names. See section\n *Special method names*.\n\n Special attributes: ``__dict__`` is the attribute dictionary;\n ``__class__`` is the instance\'s class.\n\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\n (and perhaps by other functions or methods provided by extension\n modules). The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are initialized to file objects corresponding to the\n interpreter\'s standard input, output and error streams. See *File\n Objects* for 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\n name; ``co_argcount`` is the number of positional arguments\n (including arguments with default values); ``co_nlocals`` is the\n number of local variables used by the function (including\n arguments); ``co_varnames`` is a tuple containing the names of\n the local variables (starting with the argument names);\n ``co_cellvars`` is a tuple containing the names of local\n variables that are referenced by nested functions;\n ``co_freevars`` is a tuple containing the names of free\n variables; ``co_code`` is a string representing the sequence of\n bytecode instructions; ``co_consts`` is a tuple containing the\n literals used by the bytecode; ``co_names`` is a tuple\n containing the names used by the bytecode; ``co_filename`` is\n the filename from which the code was compiled;\n ``co_firstlineno`` is the first line number of the function;\n ``co_lnotab`` is a string encoding the mapping from bytecode\n offsets to line numbers (for details see the source code of the\n interpreter); ``co_stacksize`` is the required stack size\n (including local variables); ``co_flags`` is an integer encoding\n a number of flags for the interpreter.\n\n The following flag bits are defined for ``co_flags``: bit\n ``0x04`` is set if the function uses the ``*arguments`` syntax\n to accept an arbitrary number of positional arguments; bit\n ``0x08`` is set if the function uses the ``**keywords`` syntax\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\n the function is a generator.\n\n Future feature declarations (``from __future__ import\n division``) also use bits in ``co_flags`` to indicate whether a\n code object was compiled with a particular feature enabled: bit\n ``0x2000`` is set if the function was compiled with future\n division enabled; bits ``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n Other bits in ``co_flags`` are reserved for internal use.\n\n If a code object represents a function, the first item in\n ``co_consts`` is the documentation string of the function, or\n ``None`` if undefined.\n\n Frame objects\n Frame objects represent execution frames. They may occur in\n traceback objects (see below).\n\n Special read-only attributes: ``f_back`` is to the previous\n stack frame (towards the caller), or ``None`` if this is the\n bottom stack frame; ``f_code`` is the code object being executed\n in this frame; ``f_locals`` is the dictionary used to look up\n local variables; ``f_globals`` is used for global variables;\n ``f_builtins`` is used for built-in (intrinsic) names;\n ``f_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``\n is 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,\n since it works correctly when the program is using multiple\n threads. When the program contains no suitable handler, the\n stack trace is written (nicely formatted) to the standard error\n stream; if the interpreter is interactive, it is also made\n available to the user as ``sys.last_traceback``.\n\n Special read-only attributes: ``tb_next`` is the next level in\n the stack trace (towards the frame where the exception\n occurred), or ``None`` if there is no next level; ``tb_frame``\n points to the execution frame of the current level;\n ``tb_lineno`` gives the line number where the exception\n occurred; ``tb_lasti`` indicates the precise instruction. The\n line number and last instruction in the traceback may differ\n from the line number of its frame object if the exception\n occurred in a ``try`` statement with no matching except clause\n or with a finally clause.\n\n Slice objects\n Slice objects are used to represent slices 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\n the built-in ``slice()`` function.\n\n Special read-only attributes: ``start`` is the lower bound;\n ``stop`` is the upper bound; ``step`` is the step value; each is\n ``None`` if omitted. These attributes can have any type.\n\n Slice objects support one method:\n\n slice.indices(self, length)\n\n This method takes a single integer argument *length* and\n computes information about the 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',
+ '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``.\n It is used to signify the absence of a value in many situations,\n e.g., it is returned from functions that don\'t explicitly return\n anything. Its truth value is false.\n\nNotImplemented\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``NotImplemented``. Numeric methods and rich comparison methods may\n return this value if they do not implement the operation for the\n operands provided. (The interpreter will then try the reflected\n operation, or some other fallback, depending on the operator.) Its\n truth value is true.\n\nEllipsis\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``Ellipsis``. It is used to indicate the presence of the ``...``\n syntax 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 only\n 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 is\n dwarfed by the overhead of using objects in Python, so there is\n no reason to complicate the language with two kinds of floating\n point numbers.\n\n ``numbers.Complex``\n These represent complex numbers as a pair of machine-level\n double precision floating point numbers. The same caveats apply\n as for floating point numbers. The real and imaginary parts of a\n complex number ``z`` can be retrieved through the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n These represent finite ordered sets indexed by non-negative\n numbers. The built-in function ``len()`` returns the number of\n items of a sequence. When the length of a sequence is *n*, the\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by ``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\n expression, a slice is a sequence of the same type. This implies\n that the index set is renumbered so that it starts at 0.\n\n Some sequences also support "extended slicing" with a third "step"\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n *j*.\n\n Sequences are distinguished according to their mutability:\n\n Immutable sequences\n An object of an immutable sequence type cannot change once it is\n created. (If the object contains references to other objects,\n these other objects may be mutable and may be changed; however,\n the collection of objects directly referenced by an immutable\n object cannot change.)\n\n The following types are immutable sequences:\n\n Strings\n The items of a string 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\n built-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\n a 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\n immutable and *hashable*, it can be used again as an element of\n another set, or as a dictionary key.\n\nMappings\n These represent finite sets of objects indexed by arbitrary index\n sets. The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from the mapping ``a``; this can be used in expressions and\n as the target of assignments or ``del`` statements. The built-in\n function ``len()`` returns the number of items in a mapping.\n\n There is currently a single intrinsic mapping type:\n\n Dictionaries\n These represent finite sets of objects indexed by nearly\n arbitrary values. The only types of values not acceptable as\n keys are values containing lists or dictionaries or other\n mutable types that are compared by value rather than by object\n identity, the reason being that the efficient implementation of\n dictionaries requires a key\'s hash value to remain constant.\n Numeric types used for keys obey the normal rules for numeric\n comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``) then they can be used interchangeably to index the same\n dictionary entry.\n\n Dictionaries are mutable; they can be created by the ``{...}``\n notation (see section *Dictionary displays*).\n\n The extension modules ``dbm``, ``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 | ``func_doc`` | The function\'s documentation | Writable |\n | | string, or ``None`` if | |\n | | unavailable | |\n +-------------------------+---------------------------------+-------------+\n | ``__doc__`` | Another way of spelling | Writable |\n | | ``func_doc`` | |\n +-------------------------+---------------------------------+-------------+\n | ``func_name`` | The function\'s name | Writable |\n +-------------------------+---------------------------------+-------------+\n | ``__name__`` | Another way of spelling | Writable |\n | | ``func_name`` | |\n +-------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_defaults`` | A tuple containing default | Writable |\n | | argument values for those | |\n | | arguments that have defaults, | |\n | | or ``None`` if no arguments | |\n | | have a default value | |\n +-------------------------+---------------------------------+-------------+\n | ``func_code`` | The code object representing | Writable |\n | | the compiled function body. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_globals`` | A reference to the dictionary | Read-only |\n | | that holds the function\'s | |\n | | global variables --- the global | |\n | | namespace of the module in | |\n | | which the function was defined. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_dict`` | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_closure`` | ``None`` or a tuple of cells | Read-only |\n | | that 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 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\n for 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\n the 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 3.0 forward-compatibility,\n ``im_func`` is also available as ``__func__``, and ``im_self``\n as ``__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\n unbound. When one is created by retrieving a user-defined\n function object from a class via one of its instances, its\n ``im_self`` attribute is the instance, and the method object is\n said to be bound. In either case, the new method\'s ``im_class``\n attribute is the class from which the retrieval takes place, and\n its ``im_func`` 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 (the same as the ``im_class``\n attribute), and its ``im_func`` attribute is the function object\n 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\n restriction that the first argument must be an instance of the\n proper class (``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\n a function ``f()``, and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` 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\n ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note that the transformation from function object to (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\n the end, a ``StopIteration`` exception is raised and the\n iterator will have reached the end of the set of values to be\n returned.\n\n Built-in functions\n A built-in function object is a wrapper around a C function.\n Examples of built-in functions are ``len()`` and ``math.sin()``\n (``math`` is a standard built-in module). The number and type of\n the arguments are determined by the C function. Special read-\n only attributes: ``__doc__`` is the function\'s documentation\n string, or ``None`` if unavailable; ``__name__`` is the\n function\'s name; ``__self__`` is set to ``None`` (but see the\n next item); ``__module__`` is the name of the module the\n function was defined in or ``None`` if unavailable.\n\n Built-in methods\n This is really a different disguise of a built-in function, this\n time containing an object passed to the C function as an\n implicit extra argument. An example of a built-in method is\n ``alist.append()``, assuming *alist* is a list object. In this\n case, the special read-only attribute ``__self__`` is set to the\n object denoted by *alist*.\n\n 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,\n the 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\n name; ``__doc__`` is the module\'s documentation string, or ``None``\n if unavailable; ``__file__`` is the pathname of the file from which\n the module was loaded, if it was loaded from a file. The\n ``__file__`` attribute is not present for C modules that are\n statically linked into the interpreter; for extension modules\n loaded dynamically from a shared library, it is the pathname of the\n shared library file.\n\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\n translated to ``C.__dict__["x"]`` (although for new-style classes\n in particular there are a number of hooks which allow for other\n means of locating attributes). When the attribute name is not found\n there, the attribute search continues in the base classes. For\n old-style classes, the search is depth-first, left-to-right in the\n order of occurrence in the base class list. New-style classes use\n the more complex C3 method resolution order which behaves correctly\n even in the presence of \'diamond\' inheritance structures where\n there are multiple inheritance paths leading back to a common\n ancestor. Additional details on the C3 MRO used by new-style\n classes can be found in the documentation accompanying the 2.3\n release at http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a 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_class`` and ``im_self`` attributes are\n both ``C``. When it would yield a static method object, it is\n transformed into the object wrapped by the static method object.\n See section *Implementing Descriptors* for another way in which\n attributes retrieved from a class may differ from those actually\n contained in its ``__dict__`` (note that only new-style classes\n 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__``\n is the module name in which the class was defined; ``__dict__`` is\n the dictionary containing the class\'s namespace; ``__bases__`` is a\n tuple (possibly empty or a singleton) containing the base classes,\n in the order of their occurrence in the base class list;\n ``__doc__`` is the class\'s documentation string, or None if\n undefined.\n\nClass instances\n A class instance is created by calling a class object (see above).\n A class instance has a namespace implemented as a dictionary which\n is the first place in which attribute references are searched.\n When an attribute is not found there, and the instance\'s class has\n an attribute by that name, the search continues with the class\n attributes. If a class attribute is found that is a user-defined\n function object 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\n the 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\n instead of updating the instance dictionary directly.\n\n Class instances can pretend to be numbers, sequences, or mappings\n if they have methods with certain special names. See section\n *Special method names*.\n\n Special attributes: ``__dict__`` is the attribute dictionary;\n ``__class__`` is the instance\'s class.\n\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\n (and perhaps by other functions or methods provided by extension\n modules). The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are initialized to file objects corresponding to the\n interpreter\'s standard input, output and error streams. See *File\n Objects* for 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\n name; ``co_argcount`` is the number of positional arguments\n (including arguments with default values); ``co_nlocals`` is the\n number of local variables used by the function (including\n arguments); ``co_varnames`` is a tuple containing the names of\n the local variables (starting with the argument names);\n ``co_cellvars`` is a tuple containing the names of local\n variables that are referenced by nested functions;\n ``co_freevars`` is a tuple containing the names of free\n variables; ``co_code`` is a string representing the sequence of\n bytecode instructions; ``co_consts`` is a tuple containing the\n literals used by the bytecode; ``co_names`` is a tuple\n containing the names used by the bytecode; ``co_filename`` is\n the filename from which the code was compiled;\n ``co_firstlineno`` is the first line number of the function;\n ``co_lnotab`` is a string encoding the mapping from bytecode\n offsets to line numbers (for details see the source code of the\n interpreter); ``co_stacksize`` is the required stack size\n (including local variables); ``co_flags`` is an integer encoding\n a number of flags for the interpreter.\n\n The following flag bits are defined for ``co_flags``: bit\n ``0x04`` is set if the function uses the ``*arguments`` syntax\n to accept an arbitrary number of positional arguments; bit\n ``0x08`` is set if the function uses the ``**keywords`` syntax\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\n the function is a generator.\n\n Future feature declarations (``from __future__ import\n division``) also use bits in ``co_flags`` to indicate whether a\n code object was compiled with a particular feature enabled: bit\n ``0x2000`` is set if the function was compiled with future\n division enabled; bits ``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n Other bits in ``co_flags`` are reserved for internal use.\n\n If a code object represents a function, the first item in\n ``co_consts`` is the documentation string of the function, or\n ``None`` if undefined.\n\n Frame objects\n Frame objects represent execution frames. They may occur in\n traceback objects (see below).\n\n Special read-only attributes: ``f_back`` is to the previous\n stack frame (towards the caller), or ``None`` if this is the\n bottom stack frame; ``f_code`` is the code object being executed\n in this frame; ``f_locals`` is the dictionary used to look up\n local variables; ``f_globals`` is used for global variables;\n ``f_builtins`` is used for built-in (intrinsic) names;\n ``f_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``\n is 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,\n since it works correctly when the program is using multiple\n threads. When the program contains no suitable handler, the\n stack trace is written (nicely formatted) to the standard error\n stream; if the interpreter is interactive, it is also made\n available to the user as ``sys.last_traceback``.\n\n Special read-only attributes: ``tb_next`` is the next level in\n the stack trace (towards the frame where the exception\n occurred), or ``None`` if there is no next level; ``tb_frame``\n points to the execution frame of the current level;\n ``tb_lineno`` gives the line number where the exception\n occurred; ``tb_lasti`` indicates the precise instruction. The\n line number and last instruction in the traceback may differ\n from the line number of its frame object if the exception\n occurred in a ``try`` statement with no matching except clause\n or with a finally clause.\n\n Slice objects\n Slice objects are used to represent slices 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\n the built-in ``slice()`` function.\n\n Special read-only attributes: ``start`` is the lower bound;\n ``stop`` is the upper bound; ``step`` is the step value; each is\n ``None`` if omitted. These attributes can have any type.\n\n Slice objects support one method:\n\n slice.indices(self, length)\n\n This method takes a single integer argument *length* and\n computes information about the 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``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values. Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys. Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry. (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n Return a new dictionary initialized from an optional positional\n argument or from a set of keyword arguments. If no arguments are\n given, return a new empty dictionary. If the positional argument\n *arg* is a mapping object, return a dictionary mapping the same\n keys to the same values as does the mapping object. Otherwise the\n positional argument must be a sequence, a container that supports\n iteration, or an iterator object. The elements of the argument\n must each also be of one of those kinds, and each must in turn\n contain exactly two objects. The first is used as a key in the new\n dictionary, and the second as the key\'s value. If a given key is\n seen more than once, the last value associated with it is retained\n in the new dictionary.\n\n If keyword arguments are given, the keywords themselves with their\n associated values are added as items to the dictionary. If a key is\n specified both in the positional argument and as a keyword\n argument, the value associated with the keyword is retained in the\n dictionary. For example, these all return a dictionary equal to\n ``{"one": 2, "two": 3}``:\n\n * ``dict(one=2, two=3)``\n\n * ``dict({\'one\': 2, \'two\': 3})``\n\n * ``dict(zip((\'one\', \'two\'), (2, 3)))``\n\n * ``dict([[\'two\', 3], [\'one\', 2]])``\n\n The first example only works for keys that are valid Python\n identifiers; the others work with any valid keys.\n\n 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\n ``d[key]`` operation calls that method with the key *key* as\n argument. The ``d[key]`` operation then returns or raises\n whatever is returned or raised by the ``__missing__(key)`` call\n if the key is not present. No other operations or methods invoke\n ``__missing__()``. If ``__missing__()`` is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a method; it\n cannot be an instance variable. For an example, see\n ``collections.defaultdict``.\n\n d[key] = value\n\n Set ``d[key]`` to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n Return ``True`` if *d* has a key *key*, else ``False``.\n\n 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``,\n so 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)``\n 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()``,\n ``iterkeys()``, and ``itervalues()`` are called with no\n intervening modifications to the dictionary, the lists will\n directly correspond. This allows the creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs = zip(d.values(),\n d.keys())``. The same relationship holds for the ``iterkeys()``\n and ``itervalues()`` methods: ``pairs = zip(d.itervalues(),\n d.iterkeys())`` provides the same value for ``pairs``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n 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 a tuple or other iterable 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\non the dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n Return the number of entries in the dictionary.\n\niter(dictview)\n\n Return an iterator over the keys, values or items (represented as\n tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are iterated over in an arbitrary order which is\n non-random, varies across Python implementations, and depends on\n the dictionary\'s history of insertions and deletions. If keys,\n values and items views are iterated over with no intervening\n modifications to the dictionary, the order of items will directly\n correspond. This allows the creation of ``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.items()]``.\n\n Iterating views while adding or deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x* is in the underlying dictionary\'s keys,\n values or items (in the latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like. (Values views are not\ntreated as set-like since the entries are generally not unique.) Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n Return the intersection of the dictview and the other object as a\n new set.\n\ndictview | other\n\n Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n Return the difference between the dictview and the other object\n (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n Return the symmetric difference (all elements either in *dictview*\n or *other*, but not in both) of the dictview and the other object\n as a new set.\n\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',
+ '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``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values. Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys. Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry. (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n Return a new dictionary initialized from an optional positional\n argument or from a set of keyword arguments. If no arguments are\n given, return a new empty dictionary. If the positional argument\n *arg* is a mapping object, return a dictionary mapping the same\n keys to the same values as does the mapping object. Otherwise the\n positional argument must be a sequence, a container that supports\n iteration, or an iterator object. The elements of the argument\n must each also be of one of those kinds, and each must in turn\n contain exactly two objects. The first is used as a key in the new\n dictionary, and the second as the key\'s value. If a given key is\n seen more than once, the last value associated with it is retained\n in the new dictionary.\n\n If keyword arguments are given, the keywords themselves with their\n associated values are added as items to the dictionary. If a key is\n specified both in the positional argument and as a keyword\n argument, the value associated with the keyword is retained in the\n dictionary. For example, these all return a dictionary equal to\n ``{"one": 1, "two": 2}``:\n\n * ``dict(one=1, two=2)``\n\n * ``dict({\'one\': 1, \'two\': 2})``\n\n * ``dict(zip((\'one\', \'two\'), (1, 2)))``\n\n * ``dict([[\'two\', 2], [\'one\', 1]])``\n\n The first example only works for keys that are valid Python\n identifiers; the others work with any valid keys.\n\n 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\n ``d[key]`` operation calls that method with the key *key* as\n argument. The ``d[key]`` operation then returns or raises\n whatever is returned or raised by the ``__missing__(key)`` call\n if the key is not present. No other operations or methods invoke\n ``__missing__()``. If ``__missing__()`` is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a method; it\n cannot be an instance variable. For an example, see\n ``collections.defaultdict``.\n\n d[key] = value\n\n Set ``d[key]`` to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n Return ``True`` if *d* has a key *key*, else ``False``.\n\n 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``,\n so 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)``\n 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()``,\n ``iterkeys()``, and ``itervalues()`` are called with no\n intervening modifications to the dictionary, the lists will\n directly correspond. This allows the creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs = zip(d.values(),\n d.keys())``. The same relationship holds for the ``iterkeys()``\n and ``itervalues()`` methods: ``pairs = zip(d.itervalues(),\n d.iterkeys())`` provides the same value for ``pairs``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n 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\non the dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n Return the number of entries in the dictionary.\n\niter(dictview)\n\n Return an iterator over the keys, values or items (represented as\n tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are iterated over in an arbitrary order which is\n non-random, varies across Python implementations, and depends on\n the dictionary\'s history of insertions and deletions. If keys,\n values and items views are iterated over with no intervening\n modifications to the dictionary, the order of items will directly\n correspond. This allows the creation of ``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.items()]``.\n\n Iterating views while adding or deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x* is in the underlying dictionary\'s keys,\n values or items (in the latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like. (Values views are not\ntreated as set-like since the entries are generally not unique.) Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n Return the intersection of the dictview and the other object as a\n new set.\n\ndictview | other\n\n Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n Return the difference between the dictview and the other object\n (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n Return the symmetric difference (all elements either in *dictview*\n or *other*, but not in both) of the dictview and the other object\n as a new set.\n\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\nlists) and class instance methods. Built-in methods are described\nwith the types 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\nwill be ``None`` and if called, an explicit ``self`` object must be\npassed as the first argument. In this case, ``self`` must be an\ninstance of the unbound method's class (or a subclass of that class),\notherwise a ``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 a method attribute results in a ``TypeError`` being\nraised. In order to set a method attribute, you need to explicitly\nset it on the underlying function object:\n\n class C:\n def method(self):\n pass\n\n c = C()\n c.method.im_func.whoami = 'my name is c'\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:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to. (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special member of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ``<module\n'sys' (built-in)>``. If loaded from a file, they are written as\n``<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>``.\n",
- 'typesseq': u'\nSequence Types --- ``str``, ``unicode``, ``list``, ``tuple``, ``buffer``, ``xrange``\n************************************************************************************\n\nThere are six sequence types: strings, Unicode strings, lists, tuples,\nbuffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``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\naddition to the functionality described here, there are also string-\nspecific methods 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\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\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\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*\'th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must 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 the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n 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.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbuffer, xrange* section. To output formatted strings use template\nstrings or the ``%`` operator described in the *String Formatting\nOperations* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with only its first character\n capitalized.\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\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n 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\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n 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. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3.0,\n and should be preferred to the ``%`` formatting described in\n *String 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 in the string are lowercase and\n 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 in the string are uppercase and\n 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\n ``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 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*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\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\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is 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, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\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\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\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.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\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 ``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,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(#)03d quote types.\' % \\\n... {\'language\': "Python", "#": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using ``repr()``). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (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\nnot assume 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\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList objects support additional operations that allow in-place\nmodification of the object. Other mutable sequence types (when added\nto the language) should also support these operations. Strings and\ntuples are immutable sequence types: such objects cannot be modified\nonce created. The following operations are defined on mutable sequence\ntypes (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)] = | (2) |\n| | [x]`` | |\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 multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n 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 negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments 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\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n 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\n to 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 be\n 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 sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n',
- 'typesseq-mutable': u"\nMutable Sequence Types\n**********************\n\nList objects support additional operations that allow in-place\nmodification of the object. Other mutable sequence types (when added\nto the language) should also support these operations. Strings and\ntuples are immutable sequence types: such objects cannot be modified\nonce created. The following operations are defined on mutable sequence\ntypes (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)] = | (2) |\n| | [x]`` | |\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 multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n 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 negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments 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\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n 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\n to 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 be\n 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 sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated 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,\nand the ``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\naddition to the functionality described here, there are also string-\nspecific methods 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\n``()``. A single item tuple must have a trailing comma, such as\n``(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\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*\'th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.index(i)`` | index of the first occurence of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.count(i)`` | total number of occurences of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must 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 the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n 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\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n 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\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n 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. The column number is reset to zero after each\n newline occurring in the string. If *tabsize* is not given, a tab\n size of ``8`` characters is assumed. This doesn\'t understand other\n non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\n Note: The ``find()`` method should be used only if you need to know the\n position of *sub*. To check if *sub* is a substring or not, use\n 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.0,\n and should be preferred to the ``%`` formatting described in\n *String 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 in the string are lowercase and\n 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 in the string are uppercase and\n 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\n ``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 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*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than\n ``len(s)``.\n\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\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is 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, then there is no limit\n on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\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\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\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.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string converted to uppercase.\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 ``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,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that that can be used to form decimal-radix\n numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(number)03d quote types.\' % \\\n... {"language": "Python", "number": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using ``repr()``). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (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\nnot assume 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\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\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\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable 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)] = | (2) |\n| | [x]`` | |\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 multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n 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 negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments 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\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n 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\n to 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 be\n 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 sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n',
+ 'typesseq-mutable': u"\nMutable Sequence Types\n**********************\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable 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)] = | (2) |\n| | [x]`` | |\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 multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n 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 negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments 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\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n 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\n to 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 be\n 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 sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated 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\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n',
- '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\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n',
+ '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\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the **with_item**)\n is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n',
'yield': u'\nThe ``yield`` statement\n***********************\n\n yield_stmt ::= yield_expression\n\nThe ``yield`` statement is only used when defining a generator\nfunction, and is only used in the body of the generator function.\nUsing a ``yield`` statement in a function definition is sufficient to\ncause that definition to create a generator function instead of a\nnormal function.\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\n``next()``\'s caller. By "frozen" we mean that all local state is\nretained, including the current bindings of local variables, the\ninstruction pointer, and the internal evaluation stack: enough\ninformation is saved so that the next time ``next()`` is invoked, the\nfunction can proceed exactly as if the ``yield`` statement were just\nanother external call.\n\nAs of Python version 2.5, the ``yield`` statement is now allowed in\nthe ``try`` clause of a ``try`` ... ``finally`` construct. If the\ngenerator is not resumed before it is finalized (by reaching a zero\nreference count or by being garbage collected), the generator-\niterator\'s ``close()`` method will be called, allowing any pending\n``finally`` clauses to execute.\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:\n\n **PEP 0255** - Simple Generators\n The proposal for adding generators and the ``yield`` statement\n to 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``\n block.\n'}
diff --git a/Lib/random.py b/Lib/random.py
index 1ab75d5..36b9565 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -317,7 +317,7 @@
n = len(population)
if not 0 <= k <= n:
- raise ValueError, "sample larger than population"
+ raise ValueError("sample larger than population")
random = self.random
_int = int
result = [None] * k
@@ -427,11 +427,9 @@
# lambd: rate lambd = 1/mean
# ('lambda' is a Python reserved word)
- random = self.random
- u = random()
- while u <= 1e-7:
- u = random()
- return -_log(u)/lambd
+ # we use 1-random() instead of random() to preclude the
+ # possibility of taking the log of zero.
+ return -_log(1.0 - self.random())/lambd
## -------------------- von Mises distribution --------------------
diff --git a/Lib/shutil.py b/Lib/shutil.py
index f2d2a90..be83251 100644
--- a/Lib/shutil.py
+++ b/Lib/shutil.py
@@ -25,7 +25,8 @@
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
"copytree", "move", "rmtree", "Error", "SpecialFileError",
"ExecError", "make_archive", "get_archive_formats",
- "register_archive_format", "unregister_archive_format"]
+ "register_archive_format", "unregister_archive_format",
+ "ignore_patterns"]
class Error(EnvironmentError):
pass
@@ -277,6 +278,12 @@
"""
real_dst = dst
if os.path.isdir(dst):
+ if _samefile(src, dst):
+ # We might be on a case insensitive filesystem,
+ # perform the rename anyway.
+ os.rename(src, dst)
+ return
+
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
@@ -353,7 +360,8 @@
archive_dir = os.path.dirname(archive_name)
if not os.path.exists(archive_dir):
- logger.info("creating %s" % archive_dir)
+ if logger is not None:
+ logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
diff --git a/Lib/smtplib.py b/Lib/smtplib.py
index e7d3786..07582f6 100755
--- a/Lib/smtplib.py
+++ b/Lib/smtplib.py
@@ -149,6 +149,13 @@
else:
return "<%s>" % m
+def _addr_only(addrstring):
+ displayname, addr = email.utils.parseaddr(addrstring)
+ if (displayname, addr) == ('', ''):
+ # parseaddr couldn't parse it, so use it as is.
+ return addrstring
+ return addr
+
def quotedata(data):
"""Quote data for email.
@@ -222,6 +229,7 @@
ehlo_msg = "ehlo"
ehlo_resp = None
does_esmtp = 0
+ default_port = SMTP_PORT
def __init__(self, host='', port=0, local_hostname=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
@@ -237,7 +245,6 @@
"""
self.timeout = timeout
self.esmtp_features = {}
- self.default_port = SMTP_PORT
if host:
(code, msg) = self.connect(host, port)
if code != 220:
@@ -345,8 +352,10 @@
while 1:
try:
line = self.file.readline()
- except socket.error:
- line = ''
+ except socket.error as e:
+ self.close()
+ raise SMTPServerDisconnected("Connection unexpectedly closed: "
+ + str(e))
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed")
@@ -497,14 +506,14 @@
def verify(self, address):
"""SMTP 'verify' command -- checks for address validity."""
- self.putcmd("vrfy", quoteaddr(address))
+ self.putcmd("vrfy", _addr_only(address))
return self.getreply()
# a.k.a.
vrfy = verify
def expn(self, address):
"""SMTP 'expn' command -- expands a mailing list."""
- self.putcmd("expn", quoteaddr(address))
+ self.putcmd("expn", _addr_only(address))
return self.getreply()
# some useful methods
@@ -756,13 +765,15 @@
are also optional - they can contain a PEM formatted private key and
certificate chain file for the SSL connection.
"""
+
+ default_port = SMTP_SSL_PORT
+
def __init__(self, host='', port=0, local_hostname=None,
keyfile=None, certfile=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.keyfile = keyfile
self.certfile = certfile
SMTP.__init__(self, host, port, local_hostname, timeout)
- self.default_port = SMTP_SSL_PORT
def _get_socket(self, host, port, timeout):
if self.debuglevel > 0:
diff --git a/Lib/ssl.py b/Lib/ssl.py
index 72fbae5..f3e5123 100644
--- a/Lib/ssl.py
+++ b/Lib/ssl.py
@@ -62,7 +62,6 @@
from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
from _ssl import SSLError
from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
-from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
from _ssl import RAND_status, RAND_egd, RAND_add
from _ssl import \
SSL_ERROR_ZERO_RETURN, \
@@ -74,6 +73,18 @@
SSL_ERROR_WANT_CONNECT, \
SSL_ERROR_EOF, \
SSL_ERROR_INVALID_ERROR_CODE
+from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
+_PROTOCOL_NAMES = {
+ PROTOCOL_TLSv1: "TLSv1",
+ PROTOCOL_SSLv23: "SSLv23",
+ PROTOCOL_SSLv3: "SSLv3",
+}
+try:
+ from _ssl import PROTOCOL_SSLv2
+except ImportError:
+ pass
+else:
+ _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
from socket import socket, _fileobject, _delegate_methods, error as socket_error
from socket import getnameinfo as _getnameinfo
@@ -425,16 +436,7 @@
return DER_cert_to_PEM_cert(dercert)
def get_protocol_name(protocol_code):
- if protocol_code == PROTOCOL_TLSv1:
- return "TLSv1"
- elif protocol_code == PROTOCOL_SSLv23:
- return "SSLv23"
- elif protocol_code == PROTOCOL_SSLv2:
- return "SSLv2"
- elif protocol_code == PROTOCOL_SSLv3:
- return "SSLv3"
- else:
- return "<unknown>"
+ return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
# a replacement for the old socket.ssl function
diff --git a/Lib/stat.py b/Lib/stat.py
index 4a9d30c..abed5c9 100644
--- a/Lib/stat.py
+++ b/Lib/stat.py
@@ -87,6 +87,8 @@
UF_APPEND = 0x00000004
UF_OPAQUE = 0x00000008
UF_NOUNLINK = 0x00000010
+UF_COMPRESSED = 0x00000020 # OS X: file is hfs-compressed
+UF_HIDDEN = 0x00008000 # OS X: file should not be displayed
SF_ARCHIVED = 0x00010000
SF_IMMUTABLE = 0x00020000
SF_APPEND = 0x00040000
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
index 25248dc..f0ef30e 100644
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -441,8 +441,15 @@
"check_output", "CalledProcessError"]
if mswindows:
- from _subprocess import CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
- __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP"])
+ from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
+ STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
+ STD_ERROR_HANDLE, SW_HIDE,
+ STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
+
+ __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
+ "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
+ "STD_ERROR_HANDLE", "SW_HIDE",
+ "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
@@ -453,7 +460,7 @@
def _cleanup():
for inst in _active[:]:
res = inst._internal_poll(_deadstate=sys.maxint)
- if res is not None and res >= 0:
+ if res is not None:
try:
_active.remove(inst)
except ValueError:
@@ -469,7 +476,7 @@
while True:
try:
return func(*args)
- except OSError, e:
+ except (OSError, IOError) as e:
if e.errno == errno.EINTR:
continue
raise
@@ -700,7 +707,10 @@
def __del__(self, _maxint=sys.maxint, _active=_active):
- if not self._child_created:
+ # If __init__ hasn't had a chance to execute (e.g. if it
+ # was passed an undeclared keyword argument), we don't
+ # have a _child_created attribute at all.
+ if not getattr(self, '_child_created', False):
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
@@ -733,10 +743,10 @@
raise
self.stdin.close()
elif self.stdout:
- stdout = self.stdout.read()
+ stdout = _eintr_retry_call(self.stdout.read)
self.stdout.close()
elif self.stderr:
- stderr = self.stderr.read()
+ stderr = _eintr_retry_call(self.stderr.read)
self.stderr.close()
self.wait()
return (stdout, stderr)
@@ -1025,7 +1035,7 @@
if stdin is None:
pass
elif stdin == PIPE:
- p2cread, p2cwrite = os.pipe()
+ p2cread, p2cwrite = self.pipe_cloexec()
elif isinstance(stdin, int):
p2cread = stdin
else:
@@ -1035,7 +1045,7 @@
if stdout is None:
pass
elif stdout == PIPE:
- c2pread, c2pwrite = os.pipe()
+ c2pread, c2pwrite = self.pipe_cloexec()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
@@ -1045,7 +1055,7 @@
if stderr is None:
pass
elif stderr == PIPE:
- errread, errwrite = os.pipe()
+ errread, errwrite = self.pipe_cloexec()
elif stderr == STDOUT:
errwrite = c2pwrite
elif isinstance(stderr, int):
@@ -1072,6 +1082,18 @@
fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
+ def pipe_cloexec(self):
+ """Create a pipe with FDs set CLOEXEC."""
+ # Pipes' FDs are set CLOEXEC by default because we don't want them
+ # to be inherited by other subprocesses: the CLOEXEC flag is removed
+ # from the child's FDs by _dup2(), between fork() and exec().
+ # This is not atomic: we would need the pipe2() syscall for that.
+ r, w = os.pipe()
+ self._set_cloexec_flag(r)
+ self._set_cloexec_flag(w)
+ return r, w
+
+
def _close_fds(self, but):
if hasattr(os, 'closerange'):
os.closerange(3, but)
@@ -1110,11 +1132,9 @@
# For transferring possible exec failure from child to parent
# The first char specifies the exception type: 0 means
# OSError, 1 means some other error.
- errpipe_read, errpipe_write = os.pipe()
+ errpipe_read, errpipe_write = self.pipe_cloexec()
try:
try:
- self._set_cloexec_flag(errpipe_write)
-
gc_was_enabled = gc.isenabled()
# Disable gc to avoid bug where gc -> file_dealloc ->
# write to stderr -> hang. http://bugs.python.org/issue1336
@@ -1138,6 +1158,14 @@
os.close(errread)
os.close(errpipe_read)
+ # When duping fds, if there arises a situation
+ # where one of the fds is either 0, 1 or 2, it
+ # is possible that it is overwritten (#12607).
+ if c2pwrite == 0:
+ c2pwrite = os.dup(c2pwrite)
+ if errwrite == 0 or errwrite == 1:
+ errwrite = os.dup(errwrite)
+
# Dup fds for child
def _dup2(a, b):
# dup2() removes the CLOEXEC flag but
diff --git a/Lib/sysconfig.py b/Lib/sysconfig.py
index 77402d8..9e8acc5 100644
--- a/Lib/sysconfig.py
+++ b/Lib/sysconfig.py
@@ -297,21 +297,6 @@
msg = msg + " (%s)" % e.strerror
raise IOError(msg)
- # On MacOSX we need to check the setting of the environment variable
- # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
- # it needs to be compatible.
- # If it isn't set we set it to the configure-time value
- if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in vars:
- cfg_target = vars['MACOSX_DEPLOYMENT_TARGET']
- cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
- if cur_target == '':
- cur_target = cfg_target
- os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
- elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
- msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" '
- 'during configure' % (cur_target, cfg_target))
- raise IOError(msg)
-
# On AIX, there are wrong paths to the linker scripts in the Makefile
# -- these paths are relative to the Python source, but when installed
# the scripts are in another directory.
@@ -616,9 +601,7 @@
# machine is going to compile and link as if it were
# MACOSX_DEPLOYMENT_TARGET.
cfgvars = get_config_vars()
- macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
- if not macver:
- macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
+ macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
if 1:
# Always calculate the release of the running machine,
@@ -639,7 +622,6 @@
m = re.search(
r'<key>ProductUserVisibleVersion</key>\s*' +
r'<string>(.*?)</string>', f.read())
- f.close()
if m is not None:
macrelease = '.'.join(m.group(1).split('.')[:2])
# else: fall back to the default behaviour
diff --git a/Lib/tarfile.py b/Lib/tarfile.py
index 47be1d4..6828eab 100644
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -30,7 +30,7 @@
"""Read from and write to tar format archives.
"""
-__version__ = "$Revision$"
+__version__ = "$Revision: 85213 $"
# $Source$
version = "0.9.0"
@@ -2239,10 +2239,14 @@
if hasattr(os, "symlink") and hasattr(os, "link"):
# For systems that support symbolic and hard links.
if tarinfo.issym():
+ if os.path.lexists(targetpath):
+ os.unlink(targetpath)
os.symlink(tarinfo.linkname, targetpath)
else:
# See extract().
if os.path.exists(tarinfo._link_target):
+ if os.path.lexists(targetpath):
+ os.unlink(targetpath)
os.link(tarinfo._link_target, targetpath)
else:
self._extract_member(self._find_link_target(tarinfo), targetpath)
@@ -2260,17 +2264,11 @@
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
- try:
- g = grp.getgrgid(tarinfo.gid)[2]
- except KeyError:
- g = os.getgid()
+ g = tarinfo.gid
try:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
- try:
- u = pwd.getpwuid(tarinfo.uid)[2]
- except KeyError:
- u = os.getuid()
+ u = tarinfo.uid
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
diff --git a/Lib/test/cjkencodings/big5-utf8.txt b/Lib/test/cjkencodings/big5-utf8.txt
new file mode 100644
index 0000000..a0a534a
--- /dev/null
+++ b/Lib/test/cjkencodings/big5-utf8.txt
@@ -0,0 +1,9 @@
+如何在 Python 中使用既有的 C library?
+ 在資訊科技快速發展的今天, 開發及測試軟體的速度是不容忽視的
+課題. 為加快開發及測試的速度, 我們便常希望能利用一些已開發好的
+library, 並有一個 fast prototyping 的 programming language 可
+供使用. 目前有許許多多的 library 是以 C 寫成, 而 Python 是一個
+fast prototyping 的 programming language. 故我們希望能將既有的
+C library 拿到 Python 的環境中測試及整合. 其中最主要也是我們所
+要討論的問題就是:
+
diff --git a/Lib/test/cjkencodings/big5.txt b/Lib/test/cjkencodings/big5.txt
new file mode 100644
index 0000000..f442495
--- /dev/null
+++ b/Lib/test/cjkencodings/big5.txt
@@ -0,0 +1,9 @@
+¦p¦ó¦b Python ¤¤¨Ï¥Î¬J¦³ªº C library?
+¡@¦b¸ê°T¬ì§Þ§Ö³tµo®iªº¤µ¤Ñ, ¶}µo¤Î´ú¸Õ³nÅ骺³t«×¬O¤£®e©¿µøªº
+½ÒÃD. ¬°¥[§Ö¶}µo¤Î´ú¸Õªº³t«×, §ÚÌ«K±`§Æ±æ¯à§Q¥Î¤@¨Ç¤w¶}µo¦nªº
+library, ¨Ã¦³¤@Ó fast prototyping ªº programming language ¥i
+¨Ñ¨Ï¥Î. ¥Ø«e¦³³\³\¦h¦hªº library ¬O¥H C ¼g¦¨, ¦Ó Python ¬O¤@Ó
+fast prototyping ªº programming language. ¬G§Ú̧Ʊæ¯à±N¬J¦³ªº
+C library ®³¨ì Python ªºÀô¹Ò¤¤´ú¸Õ¤Î¾ã¦X. ¨ä¤¤³Ì¥Dn¤]¬O§ÚÌ©Ò
+n°Q½×ªº°ÝÃD´N¬O:
+
diff --git a/Lib/test/cjkencodings/big5hkscs-utf8.txt b/Lib/test/cjkencodings/big5hkscs-utf8.txt
new file mode 100644
index 0000000..f744ce9
--- /dev/null
+++ b/Lib/test/cjkencodings/big5hkscs-utf8.txt
@@ -0,0 +1,2 @@
+𠄌Ě鵮罓洆
+ÊÊ̄ê êê̄
diff --git a/Lib/test/cjkencodings/big5hkscs.txt b/Lib/test/cjkencodings/big5hkscs.txt
new file mode 100644
index 0000000..81c42b3
--- /dev/null
+++ b/Lib/test/cjkencodings/big5hkscs.txt
@@ -0,0 +1,2 @@
+E\sÚØ
+fb§ §£
diff --git a/Lib/test/cjkencodings/cp949-utf8.txt b/Lib/test/cjkencodings/cp949-utf8.txt
new file mode 100644
index 0000000..5655e38
--- /dev/null
+++ b/Lib/test/cjkencodings/cp949-utf8.txt
@@ -0,0 +1,9 @@
+똠방각하 펲시콜라
+
+㉯㉯납!! 因九月패믤릔궈 ⓡⓖ훀¿¿¿ 긍뒙 ⓔ뎨 ㉯. .
+亞영ⓔ능횹 . . . . 서울뤄 뎐학乙 家훀 ! ! !ㅠ.ㅠ
+흐흐흐 ㄱㄱㄱ☆ㅠ_ㅠ 어릨 탸콰긐 뎌응 칑九들乙 ㉯드긐
+설릌 家훀 . . . . 굴애쉌 ⓔ궈 ⓡ릘㉱긐 因仁川女中까즼
+와쒀훀 ! ! 亞영ⓔ 家능궈 ☆上관 없능궈능 亞능뒈훀 글애듴
+ⓡ려듀九 싀풔숴훀 어릨 因仁川女中싁⑨들앜!! ㉯㉯납♡ ⌒⌒*
+
diff --git a/Lib/test/cjkencodings/cp949.txt b/Lib/test/cjkencodings/cp949.txt
new file mode 100644
index 0000000..16549aa
--- /dev/null
+++ b/Lib/test/cjkencodings/cp949.txt
@@ -0,0 +1,9 @@
+c¹æ°¢ÇÏ ¼½ÃÄݶó
+
+¨À¨À³³!! ì×ÎúêÅÆÐæp±Å ¨Þ¨ÓÄR¢¯¢¯¢¯ ±à ¨Ñµ³ ¨À. .
+䬿µ¨Ñ´ÉÈ . . . . ¼¿ï·ï µ¯ÇÐëà Ê«ÄR ! ! !¤Ð.¤Ð
+ÈåÈåÈå ¤¡¤¡¤¡¡Ù¤Ð_¤Ð ¾î ÅËÄâO µ®ÀÀ ¯hÎúµéëà ¨ÀµåO
+¼³j Ê«ÄR . . . . ±¼¾Öf ¨Ñ±Å ¨Þt¨ÂO ì×ìÒô¹åüñé±î£
+¿Í¾¬ÄR ! ! 䬿µ¨Ñ Ê«´É±Å ¡Ùß¾°ü ¾ø´É±Å´É 䬴ɵØÄR ±Û¾ÖÛ
+¨Þ·ÁµàÎú ÃÇ´½¤ÄR ¾î ì×ìÒô¹åüñéĨïµéÚ!! ¨À¨À³³¢½ ¡Ò¡Ò*
+
diff --git a/Lib/test/cjkencodings/euc_jisx0213-utf8.txt b/Lib/test/cjkencodings/euc_jisx0213-utf8.txt
new file mode 100644
index 0000000..9a56a2e
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_jisx0213-utf8.txt
@@ -0,0 +1,8 @@
+Python の開発は、1990 年ごろから開始されています。
+開発者の Guido van Rossum は教育用のプログラミング言語「ABC」の開発に参加していましたが、ABC は実用上の目的にはあまり適していませんでした。
+このため、Guido はより実用的なプログラミング言語の開発を開始し、英国 BBS 放送のコメディ番組「モンティ パイソン」のファンである Guido はこの言語を「Python」と名づけました。
+このような背景から生まれた Python の言語設計は、「シンプル」で「習得が容易」という目標に重点が置かれています。
+多くのスクリプト系言語ではユーザの目先の利便性を優先して色々な機能を言語要素として取り入れる場合が多いのですが、Python ではそういった小細工が追加されることはあまりありません。
+言語自体の機能は最小限に押さえ、必要な機能は拡張モジュールとして追加する、というのが Python のポリシーです。
+
+ノか゚ ト゚ トキ喝塀 𡚴𪎌 麀齁𩛰
diff --git a/Lib/test/cjkencodings/euc_jisx0213.txt b/Lib/test/cjkencodings/euc_jisx0213.txt
new file mode 100644
index 0000000..51e9268
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_jisx0213.txt
@@ -0,0 +1,8 @@
+Python ¤Î³«È¯¤Ï¡¢1990 ǯ¤´¤í¤«¤é³«»Ï¤µ¤ì¤Æ¤¤¤Þ¤¹¡£
+³«È¯¼Ô¤Î Guido van Rossum ¤Ï¶µ°éÍÑ¤Î¥×¥í¥°¥é¥ß¥ó¥°¸À¸ì¡ÖABC¡×¤Î³«È¯¤Ë»²²Ã¤·¤Æ¤¤¤Þ¤·¤¿¤¬¡¢ABC ¤Ï¼ÂÍѾå¤ÎÌÜŪ¤Ë¤Ï¤¢¤Þ¤êŬ¤·¤Æ¤¤¤Þ¤»¤ó¤Ç¤·¤¿¡£
+¤³¤Î¤¿¤á¡¢Guido ¤Ï¤è¤ê¼ÂÍÑŪ¤Ê¥×¥í¥°¥é¥ß¥ó¥°¸À¸ì¤Î³«È¯¤ò³«»Ï¤·¡¢±Ñ¹ñ BBS ÊüÁ÷¤Î¥³¥á¥Ç¥£ÈÖÁȡ֥â¥ó¥Æ¥£ ¥Ñ¥¤¥½¥ó¡×¤Î¥Õ¥¡¥ó¤Ç¤¢¤ë Guido ¤Ï¤³¤Î¸À¸ì¤ò¡ÖPython¡×¤È̾¤Å¤±¤Þ¤·¤¿¡£
+¤³¤Î¤è¤¦¤ÊÇØ·Ê¤«¤éÀ¸¤Þ¤ì¤¿ Python ¤Î¸À¸ìÀ߷פϡ¢¡Ö¥·¥ó¥×¥ë¡×¤Ç¡Ö½¬ÆÀ¤¬ÍưספȤ¤¤¦ÌÜɸ¤Ë½ÅÅÀ¤¬ÃÖ¤«¤ì¤Æ¤¤¤Þ¤¹¡£
+¿¤¯¤Î¥¹¥¯¥ê¥×¥È·Ï¸À¸ì¤Ç¤Ï¥æ¡¼¥¶¤ÎÌÜÀè¤ÎÍøÊØÀ¤òÍ¥À褷¤Æ¿§¡¹¤Êµ¡Ç½¤ò¸À¸ìÍ×ÁǤȤ·¤Æ¼è¤êÆþ¤ì¤ë¾ì¹ç¤¬Â¿¤¤¤Î¤Ç¤¹¤¬¡¢Python ¤Ç¤Ï¤½¤¦¤¤¤Ã¤¿¾®ºÙ¹©¤¬Äɲ䵤ì¤ë¤³¤È¤Ï¤¢¤Þ¤ê¤¢¤ê¤Þ¤»¤ó¡£
+¸À¸ì¼«ÂΤε¡Ç½¤ÏºÇ¾®¸Â¤Ë²¡¤µ¤¨¡¢É¬Íפʵ¡Ç½¤Ï³ÈÄ¥¥â¥¸¥å¡¼¥ë¤È¤·¤ÆÄɲ乤롢¤È¤¤¤¦¤Î¤¬ Python ¤Î¥Ý¥ê¥·¡¼¤Ç¤¹¡£
+
+¥Î¤÷ ¥þ ¥È¥¯¬¯Ú ÏãþØ þÔþèüÖ
diff --git a/Lib/test/cjkencodings/euc_jp-utf8.txt b/Lib/test/cjkencodings/euc_jp-utf8.txt
new file mode 100644
index 0000000..7763250
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_jp-utf8.txt
@@ -0,0 +1,7 @@
+Python の開発は、1990 年ごろから開始されています。
+開発者の Guido van Rossum は教育用のプログラミング言語「ABC」の開発に参加していましたが、ABC は実用上の目的にはあまり適していませんでした。
+このため、Guido はより実用的なプログラミング言語の開発を開始し、英国 BBS 放送のコメディ番組「モンティ パイソン」のファンである Guido はこの言語を「Python」と名づけました。
+このような背景から生まれた Python の言語設計は、「シンプル」で「習得が容易」という目標に重点が置かれています。
+多くのスクリプト系言語ではユーザの目先の利便性を優先して色々な機能を言語要素として取り入れる場合が多いのですが、Python ではそういった小細工が追加されることはあまりありません。
+言語自体の機能は最小限に押さえ、必要な機能は拡張モジュールとして追加する、というのが Python のポリシーです。
+
diff --git a/Lib/test/cjkencodings/euc_jp.txt b/Lib/test/cjkencodings/euc_jp.txt
new file mode 100644
index 0000000..9da6b5d
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_jp.txt
@@ -0,0 +1,7 @@
+Python ¤Î³«È¯¤Ï¡¢1990 ǯ¤´¤í¤«¤é³«»Ï¤µ¤ì¤Æ¤¤¤Þ¤¹¡£
+³«È¯¼Ô¤Î Guido van Rossum ¤Ï¶µ°éÍÑ¤Î¥×¥í¥°¥é¥ß¥ó¥°¸À¸ì¡ÖABC¡×¤Î³«È¯¤Ë»²²Ã¤·¤Æ¤¤¤Þ¤·¤¿¤¬¡¢ABC ¤Ï¼ÂÍѾå¤ÎÌÜŪ¤Ë¤Ï¤¢¤Þ¤êŬ¤·¤Æ¤¤¤Þ¤»¤ó¤Ç¤·¤¿¡£
+¤³¤Î¤¿¤á¡¢Guido ¤Ï¤è¤ê¼ÂÍÑŪ¤Ê¥×¥í¥°¥é¥ß¥ó¥°¸À¸ì¤Î³«È¯¤ò³«»Ï¤·¡¢±Ñ¹ñ BBS ÊüÁ÷¤Î¥³¥á¥Ç¥£ÈÖÁȡ֥â¥ó¥Æ¥£ ¥Ñ¥¤¥½¥ó¡×¤Î¥Õ¥¡¥ó¤Ç¤¢¤ë Guido ¤Ï¤³¤Î¸À¸ì¤ò¡ÖPython¡×¤È̾¤Å¤±¤Þ¤·¤¿¡£
+¤³¤Î¤è¤¦¤ÊÇØ·Ê¤«¤éÀ¸¤Þ¤ì¤¿ Python ¤Î¸À¸ìÀ߷פϡ¢¡Ö¥·¥ó¥×¥ë¡×¤Ç¡Ö½¬ÆÀ¤¬ÍưספȤ¤¤¦ÌÜɸ¤Ë½ÅÅÀ¤¬ÃÖ¤«¤ì¤Æ¤¤¤Þ¤¹¡£
+¿¤¯¤Î¥¹¥¯¥ê¥×¥È·Ï¸À¸ì¤Ç¤Ï¥æ¡¼¥¶¤ÎÌÜÀè¤ÎÍøÊØÀ¤òÍ¥À褷¤Æ¿§¡¹¤Êµ¡Ç½¤ò¸À¸ìÍ×ÁǤȤ·¤Æ¼è¤êÆþ¤ì¤ë¾ì¹ç¤¬Â¿¤¤¤Î¤Ç¤¹¤¬¡¢Python ¤Ç¤Ï¤½¤¦¤¤¤Ã¤¿¾®ºÙ¹©¤¬Äɲ䵤ì¤ë¤³¤È¤Ï¤¢¤Þ¤ê¤¢¤ê¤Þ¤»¤ó¡£
+¸À¸ì¼«ÂΤε¡Ç½¤ÏºÇ¾®¸Â¤Ë²¡¤µ¤¨¡¢É¬Íפʵ¡Ç½¤Ï³ÈÄ¥¥â¥¸¥å¡¼¥ë¤È¤·¤ÆÄɲ乤롢¤È¤¤¤¦¤Î¤¬ Python ¤Î¥Ý¥ê¥·¡¼¤Ç¤¹¡£
+
diff --git a/Lib/test/cjkencodings/euc_kr-utf8.txt b/Lib/test/cjkencodings/euc_kr-utf8.txt
new file mode 100644
index 0000000..16c3741
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_kr-utf8.txt
@@ -0,0 +1,7 @@
+◎ 파이썬(Python)은 배우기 쉽고, 강력한 프로그래밍 언어입니다. 파이썬은
+효율적인 고수준 데이터 구조와 간단하지만 효율적인 객체지향프로그래밍을
+지원합니다. 파이썬의 우아(優雅)한 문법과 동적 타이핑, 그리고 인터프리팅
+환경은 파이썬을 스크립팅과 여러 분야에서와 대부분의 플랫폼에서의 빠른
+애플리케이션 개발을 할 수 있는 이상적인 언어로 만들어줍니다.
+
+☆첫가끝: 날아라 쓔쓔쓩~ 닁큼! 뜽금없이 전홥니다. 뷁. 그런거 읎다.
diff --git a/Lib/test/cjkencodings/euc_kr.txt b/Lib/test/cjkencodings/euc_kr.txt
new file mode 100644
index 0000000..f68dd35
--- /dev/null
+++ b/Lib/test/cjkencodings/euc_kr.txt
@@ -0,0 +1,7 @@
+¡Ý ÆÄÀ̽ã(Python)Àº ¹è¿ì±â ½±°í, °·ÂÇÑ ÇÁ·Î±×·¡¹Ö ¾ð¾îÀÔ´Ï´Ù. ÆÄÀ̽ãÀº
+È¿À²ÀûÀÎ °í¼öÁØ µ¥ÀÌÅÍ ±¸Á¶¿Í °£´ÜÇÏÁö¸¸ È¿À²ÀûÀÎ °´Ã¼ÁöÇâÇÁ·Î±×·¡¹ÖÀ»
+Áö¿øÇÕ´Ï´Ù. ÆÄÀ̽ãÀÇ ¿ì¾Æ(éÐäº)ÇÑ ¹®¹ý°ú µ¿Àû ŸÀÌÇÎ, ±×¸®°í ÀÎÅÍÇÁ¸®ÆÃ
+ȯ°æÀº ÆÄÀ̽ãÀ» ½ºÅ©¸³ÆÃ°ú ¿©·¯ ºÐ¾ß¿¡¼¿Í ´ëºÎºÐÀÇ Ç÷§Æû¿¡¼ÀÇ ºü¸¥
+¾ÖÇø®ÄÉÀÌ¼Ç °³¹ßÀ» ÇÒ ¼ö ÀÖ´Â ÀÌ»óÀûÀÎ ¾ð¾î·Î ¸¸µé¾îÁÝ´Ï´Ù.
+
+¡Ùù°¡³¡: ³¯¾Æ¶ó ¤Ô¤¶¤Ð¤Ô¤Ô¤¶¤Ð¤Ô¾±~ ¤Ô¤¤¤Ò¤·Å! ¤Ô¤¨¤Ñ¤·±Ý¾øÀÌ Àü¤Ô¤¾¤È¤²´Ï´Ù. ¤Ô¤²¤Î¤ª. ±×·±°Å ¤Ô¤·¤Ñ¤´´Ù.
diff --git a/Lib/test/cjkencodings/gb18030-utf8.txt b/Lib/test/cjkencodings/gb18030-utf8.txt
new file mode 100644
index 0000000..2060d25
--- /dev/null
+++ b/Lib/test/cjkencodings/gb18030-utf8.txt
@@ -0,0 +1,15 @@
+Python(派森)语言是一种功能强大而完善的通用型计算机程序设计语言,
+已经具有十多年的发展历史,成熟且稳定。这种语言具有非常简捷而清晰
+的语法特点,适合完成各种高层任务,几乎可以在所有的操作系统中
+运行。这种语言简单而强大,适合各种人士学习使用。目前,基于这
+种语言的相关技术正在飞速的发展,用户数量急剧扩大,相关的资源非常多。
+如何在 Python 中使用既有的 C library?
+ 在資訊科技快速發展的今天, 開發及測試軟體的速度是不容忽視的
+課題. 為加快開發及測試的速度, 我們便常希望能利用一些已開發好的
+library, 並有一個 fast prototyping 的 programming language 可
+供使用. 目前有許許多多的 library 是以 C 寫成, 而 Python 是一個
+fast prototyping 的 programming language. 故我們希望能將既有的
+C library 拿到 Python 的環境中測試及整合. 其中最主要也是我們所
+要討論的問題就是:
+파이썬은 강력한 기능을 지닌 범용 컴퓨터 프로그래밍 언어다.
+
diff --git a/Lib/test/cjkencodings/gb18030.txt b/Lib/test/cjkencodings/gb18030.txt
new file mode 100644
index 0000000..5d1f6dc
--- /dev/null
+++ b/Lib/test/cjkencodings/gb18030.txt
@@ -0,0 +1,15 @@
+Python£¨ÅÉÉ£©ÓïÑÔÊÇÒ»ÖÖ¹¦ÄÜÇ¿´ó¶øÍêÉÆµÄͨÓÃÐͼÆËã»ú³ÌÐòÉè¼ÆÓïÑÔ£¬
+ÒѾ¾ßÓÐÊ®¶àÄêµÄ·¢Õ¹ÀúÊ·£¬³ÉÊìÇÒÎȶ¨¡£ÕâÖÖÓïÑÔ¾ßÓзdz£¼ò½Ý¶øÇåÎú
+µÄÓï·¨ÌØµã£¬ÊʺÏÍê³É¸÷Öָ߲ãÈÎÎñ£¬¼¸ºõ¿ÉÒÔÔÚËùÓеIJÙ×÷ϵͳÖÐ
+ÔËÐС£ÕâÖÖÓïÑÔ¼òµ¥¶øÇ¿´ó£¬Êʺϸ÷ÖÖÈËʿѧϰʹÓá£Ä¿Ç°£¬»ùÓÚÕâ
+ÖÖÓïÑÔµÄÏà¹Ø¼¼ÊõÕýÔÚ·ÉËٵķ¢Õ¹£¬Óû§ÊýÁ¿¼±¾çÀ©´ó£¬Ïà¹ØµÄ×ÊÔ´·Ç³£¶à¡£
+ÈçºÎÔÚ Python ÖÐʹÓüÈÓÐµÄ C library?
+¡¡ÔÚÙYӿƼ¼¿ìËÙ°lÕ¹µÄ½ñÌì, é_°l¼°yÔÜówµÄËÙ¶ÈÊDz»ÈݺöÒµÄ
+Õnî}. é¼Ó¿ìé_°l¼°yÔµÄËÙ¶È, Îұ㳣ϣÍûÄÜÀûÓÃһЩÒÑé_°lºÃµÄ
+library, KÓÐÒ» fast prototyping µÄ programming language ¿É
+¹©Ê¹ÓÃ. ĿǰÓÐÔSÔS¶à¶àµÄ library ÊÇÒÔ C ³É, ¶ø Python ÊÇÒ»
+fast prototyping µÄ programming language. ¹ÊÎÒÏ£ÍûÄÜ¢¼ÈÓеÄ
+C library Äõ½ Python µÄh¾³ÖÐyÔ¼°ÕûºÏ. ÆäÖÐ×îÖ÷ÒªÒ²ÊÇÎÒËù
+ÒªÓÕµÄî}¾ÍÊÇ:
+5Ç1332±131 7Ñ60463 858û635 3Õ195 0ý930 4Ü35ö755 5ù509899ü30ð4 2ë92ë599.
+
diff --git a/Lib/test/cjkencodings/gb2312-utf8.txt b/Lib/test/cjkencodings/gb2312-utf8.txt
new file mode 100644
index 0000000..efb7d8f
--- /dev/null
+++ b/Lib/test/cjkencodings/gb2312-utf8.txt
@@ -0,0 +1,6 @@
+Python(派森)语言是一种功能强大而完善的通用型计算机程序设计语言,
+已经具有十多年的发展历史,成熟且稳定。这种语言具有非常简捷而清晰
+的语法特点,适合完成各种高层任务,几乎可以在所有的操作系统中
+运行。这种语言简单而强大,适合各种人士学习使用。目前,基于这
+种语言的相关技术正在飞速的发展,用户数量急剧扩大,相关的资源非常多。
+
diff --git a/Lib/test/cjkencodings/gb2312.txt b/Lib/test/cjkencodings/gb2312.txt
new file mode 100644
index 0000000..1536ac1
--- /dev/null
+++ b/Lib/test/cjkencodings/gb2312.txt
@@ -0,0 +1,6 @@
+Python£¨ÅÉÉ£©ÓïÑÔÊÇÒ»ÖÖ¹¦ÄÜÇ¿´ó¶øÍêÉÆµÄͨÓÃÐͼÆËã»ú³ÌÐòÉè¼ÆÓïÑÔ£¬
+ÒѾ¾ßÓÐÊ®¶àÄêµÄ·¢Õ¹ÀúÊ·£¬³ÉÊìÇÒÎȶ¨¡£ÕâÖÖÓïÑÔ¾ßÓзdz£¼ò½Ý¶øÇåÎú
+µÄÓï·¨ÌØµã£¬ÊʺÏÍê³É¸÷Öָ߲ãÈÎÎñ£¬¼¸ºõ¿ÉÒÔÔÚËùÓеIJÙ×÷ϵͳÖÐ
+ÔËÐС£ÕâÖÖÓïÑÔ¼òµ¥¶øÇ¿´ó£¬Êʺϸ÷ÖÖÈËʿѧϰʹÓá£Ä¿Ç°£¬»ùÓÚÕâ
+ÖÖÓïÑÔµÄÏà¹Ø¼¼ÊõÕýÔÚ·ÉËٵķ¢Õ¹£¬Óû§ÊýÁ¿¼±¾çÀ©´ó£¬Ïà¹ØµÄ×ÊÔ´·Ç³£¶à¡£
+
diff --git a/Lib/test/cjkencodings/gbk-utf8.txt b/Lib/test/cjkencodings/gbk-utf8.txt
new file mode 100644
index 0000000..75bbd31
--- /dev/null
+++ b/Lib/test/cjkencodings/gbk-utf8.txt
@@ -0,0 +1,14 @@
+Python(派森)语言是一种功能强大而完善的通用型计算机程序设计语言,
+已经具有十多年的发展历史,成熟且稳定。这种语言具有非常简捷而清晰
+的语法特点,适合完成各种高层任务,几乎可以在所有的操作系统中
+运行。这种语言简单而强大,适合各种人士学习使用。目前,基于这
+种语言的相关技术正在飞速的发展,用户数量急剧扩大,相关的资源非常多。
+如何在 Python 中使用既有的 C library?
+ 在資訊科技快速發展的今天, 開發及測試軟體的速度是不容忽視的
+課題. 為加快開發及測試的速度, 我們便常希望能利用一些已開發好的
+library, 並有一個 fast prototyping 的 programming language 可
+供使用. 目前有許許多多的 library 是以 C 寫成, 而 Python 是一個
+fast prototyping 的 programming language. 故我們希望能將既有的
+C library 拿到 Python 的環境中測試及整合. 其中最主要也是我們所
+要討論的問題就是:
+
diff --git a/Lib/test/cjkencodings/gbk.txt b/Lib/test/cjkencodings/gbk.txt
new file mode 100644
index 0000000..8788f8a
--- /dev/null
+++ b/Lib/test/cjkencodings/gbk.txt
@@ -0,0 +1,14 @@
+Python£¨ÅÉÉ£©ÓïÑÔÊÇÒ»ÖÖ¹¦ÄÜÇ¿´ó¶øÍêÉÆµÄͨÓÃÐͼÆËã»ú³ÌÐòÉè¼ÆÓïÑÔ£¬
+ÒѾ¾ßÓÐÊ®¶àÄêµÄ·¢Õ¹ÀúÊ·£¬³ÉÊìÇÒÎȶ¨¡£ÕâÖÖÓïÑÔ¾ßÓзdz£¼ò½Ý¶øÇåÎú
+µÄÓï·¨ÌØµã£¬ÊʺÏÍê³É¸÷Öָ߲ãÈÎÎñ£¬¼¸ºõ¿ÉÒÔÔÚËùÓеIJÙ×÷ϵͳÖÐ
+ÔËÐС£ÕâÖÖÓïÑÔ¼òµ¥¶øÇ¿´ó£¬Êʺϸ÷ÖÖÈËʿѧϰʹÓá£Ä¿Ç°£¬»ùÓÚÕâ
+ÖÖÓïÑÔµÄÏà¹Ø¼¼ÊõÕýÔÚ·ÉËٵķ¢Õ¹£¬Óû§ÊýÁ¿¼±¾çÀ©´ó£¬Ïà¹ØµÄ×ÊÔ´·Ç³£¶à¡£
+ÈçºÎÔÚ Python ÖÐʹÓüÈÓÐµÄ C library?
+¡¡ÔÚÙYӿƼ¼¿ìËÙ°lÕ¹µÄ½ñÌì, é_°l¼°yÔÜówµÄËÙ¶ÈÊDz»ÈݺöÒµÄ
+Õnî}. é¼Ó¿ìé_°l¼°yÔµÄËÙ¶È, Îұ㳣ϣÍûÄÜÀûÓÃһЩÒÑé_°lºÃµÄ
+library, KÓÐÒ» fast prototyping µÄ programming language ¿É
+¹©Ê¹ÓÃ. ĿǰÓÐÔSÔS¶à¶àµÄ library ÊÇÒÔ C ³É, ¶ø Python ÊÇÒ»
+fast prototyping µÄ programming language. ¹ÊÎÒÏ£ÍûÄÜ¢¼ÈÓеÄ
+C library Äõ½ Python µÄh¾³ÖÐyÔ¼°ÕûºÏ. ÆäÖÐ×îÖ÷ÒªÒ²ÊÇÎÒËù
+ÒªÓÕµÄî}¾ÍÊÇ:
+
diff --git a/Lib/test/cjkencodings/hz-utf8.txt b/Lib/test/cjkencodings/hz-utf8.txt
new file mode 100644
index 0000000..7c11735
--- /dev/null
+++ b/Lib/test/cjkencodings/hz-utf8.txt
@@ -0,0 +1,2 @@
+This sentence is in ASCII.
+The next sentence is in GB.己所不欲,勿施於人。Bye.
diff --git a/Lib/test/cjkencodings/hz.txt b/Lib/test/cjkencodings/hz.txt
new file mode 100644
index 0000000..f882d46
--- /dev/null
+++ b/Lib/test/cjkencodings/hz.txt
@@ -0,0 +1,2 @@
+This sentence is in ASCII.
+The next sentence is in GB.~{<:Ky2;S{#,NpJ)l6HK!#~}Bye.
diff --git a/Lib/test/cjkencodings/iso2022_jp-utf8.txt b/Lib/test/cjkencodings/iso2022_jp-utf8.txt
new file mode 100644
index 0000000..7763250
--- /dev/null
+++ b/Lib/test/cjkencodings/iso2022_jp-utf8.txt
@@ -0,0 +1,7 @@
+Python の開発は、1990 年ごろから開始されています。
+開発者の Guido van Rossum は教育用のプログラミング言語「ABC」の開発に参加していましたが、ABC は実用上の目的にはあまり適していませんでした。
+このため、Guido はより実用的なプログラミング言語の開発を開始し、英国 BBS 放送のコメディ番組「モンティ パイソン」のファンである Guido はこの言語を「Python」と名づけました。
+このような背景から生まれた Python の言語設計は、「シンプル」で「習得が容易」という目標に重点が置かれています。
+多くのスクリプト系言語ではユーザの目先の利便性を優先して色々な機能を言語要素として取り入れる場合が多いのですが、Python ではそういった小細工が追加されることはあまりありません。
+言語自体の機能は最小限に押さえ、必要な機能は拡張モジュールとして追加する、というのが Python のポリシーです。
+
diff --git a/Lib/test/cjkencodings/iso2022_jp.txt b/Lib/test/cjkencodings/iso2022_jp.txt
new file mode 100644
index 0000000..fc398d6
--- /dev/null
+++ b/Lib/test/cjkencodings/iso2022_jp.txt
@@ -0,0 +1,7 @@
+Python $B$N3+H/$O!"(B1990 $BG/$4$m$+$i3+;O$5$l$F$$$^$9!#(B
+$B3+H/<T$N(B Guido van Rossum $B$O650iMQ$N%W%m%0%i%_%s%08@8l!V(BABC$B!W$N3+H/$K;22C$7$F$$$^$7$?$,!"(BABC $B$O<BMQ>e$NL\E*$K$O$"$^$jE,$7$F$$$^$;$s$G$7$?!#(B
+$B$3$N$?$a!"(BGuido $B$O$h$j<BMQE*$J%W%m%0%i%_%s%08@8l$N3+H/$r3+;O$7!"1Q9q(B BBS $BJ|Aw$N%3%a%G%#HVAH!V%b%s%F%#(B $B%Q%$%=%s!W$N%U%!%s$G$"$k(B Guido $B$O$3$N8@8l$r!V(BPython$B!W$HL>$E$1$^$7$?!#(B
+$B$3$N$h$&$JGX7J$+$i@8$^$l$?(B Python $B$N8@8l@_7W$O!"!V%7%s%W%k!W$G!V=,F@$,MF0W!W$H$$$&L\I8$K=EE@$,CV$+$l$F$$$^$9!#(B
+$BB?$/$N%9%/%j%W%H7O8@8l$G$O%f!<%6$NL\@h$NMxJX@-$rM%@h$7$F?'!9$J5!G=$r8@8lMWAG$H$7$F<h$jF~$l$k>l9g$,B?$$$N$G$9$,!"(BPython $B$G$O$=$&$$$C$?>.:Y9)$,DI2C$5$l$k$3$H$O$"$^$j$"$j$^$;$s!#(B
+$B8@8l<+BN$N5!G=$O:G>.8B$K2!$5$(!"I,MW$J5!G=$O3HD%%b%8%e!<%k$H$7$FDI2C$9$k!"$H$$$&$N$,(B Python $B$N%]%j%7!<$G$9!#(B
+
diff --git a/Lib/test/cjkencodings/iso2022_kr-utf8.txt b/Lib/test/cjkencodings/iso2022_kr-utf8.txt
new file mode 100644
index 0000000..d5c9d6e
--- /dev/null
+++ b/Lib/test/cjkencodings/iso2022_kr-utf8.txt
@@ -0,0 +1,7 @@
+◎ 파이썬(Python)은 배우기 쉽고, 강력한 프로그래밍 언어입니다. 파이썬은
+효율적인 고수준 데이터 구조와 간단하지만 효율적인 객체지향프로그래밍을
+지원합니다. 파이썬의 우아(優雅)한 문법과 동적 타이핑, 그리고 인터프리팅
+환경은 파이썬을 스크립팅과 여러 분야에서와 대부분의 플랫폼에서의 빠른
+애플리케이션 개발을 할 수 있는 이상적인 언어로 만들어줍니다.
+
+☆첫가끝: 날아라 쓩~ 큼! 금없이 전니다. 그런거 다.
diff --git a/Lib/test/cjkencodings/iso2022_kr.txt b/Lib/test/cjkencodings/iso2022_kr.txt
new file mode 100644
index 0000000..2cece21
--- /dev/null
+++ b/Lib/test/cjkencodings/iso2022_kr.txt
@@ -0,0 +1,7 @@
+$)C!] FD@L=c(Python)@: 9h?l1b =10m, 0-7BGQ GA7N1W7!9V >p>n@T4O4Y. FD@L=c@:
+H?@2@{@N 0m<vAX 5%@LEM 18A6?M 0#4\GOAv88 H?@2@{@N 04C<AvGbGA7N1W7!9V@;
+Av?xGU4O4Y. FD@L=c@G ?l>F(iPd:)GQ 9.9}0z 5?@{ E8@LGN, 1W8.0m @NEMGA8.FC
+H/0f@: FD@L=c@; =:E)83FC0z ?)7/ :P>_?!<-?M 4k:N:P@G GC7'F{?!<-@G :|8%
+>VGC8.DI@L<G 039_@; GR <v @V4B @L;s@{@N >p>n7N 885i>nA]4O4Y.
+
+!YC90!3!: 3/>F6s >1~ E-! 1]>x@L @|4O4Y. 1W710E 4Y.
diff --git a/Lib/test/cjkencodings/johab-utf8.txt b/Lib/test/cjkencodings/johab-utf8.txt
new file mode 100644
index 0000000..5655e38
--- /dev/null
+++ b/Lib/test/cjkencodings/johab-utf8.txt
@@ -0,0 +1,9 @@
+똠방각하 펲시콜라
+
+㉯㉯납!! 因九月패믤릔궈 ⓡⓖ훀¿¿¿ 긍뒙 ⓔ뎨 ㉯. .
+亞영ⓔ능횹 . . . . 서울뤄 뎐학乙 家훀 ! ! !ㅠ.ㅠ
+흐흐흐 ㄱㄱㄱ☆ㅠ_ㅠ 어릨 탸콰긐 뎌응 칑九들乙 ㉯드긐
+설릌 家훀 . . . . 굴애쉌 ⓔ궈 ⓡ릘㉱긐 因仁川女中까즼
+와쒀훀 ! ! 亞영ⓔ 家능궈 ☆上관 없능궈능 亞능뒈훀 글애듴
+ⓡ려듀九 싀풔숴훀 어릨 因仁川女中싁⑨들앜!! ㉯㉯납♡ ⌒⌒*
+
diff --git a/Lib/test/cjkencodings/johab.txt b/Lib/test/cjkencodings/johab.txt
new file mode 100644
index 0000000..067781b
--- /dev/null
+++ b/Lib/test/cjkencodings/johab.txt
@@ -0,0 +1,9 @@
+±¤wbÐa Í\¯¡Å©a
+
+ÜÀÜÀs!! ñgâðUÌ£
¡ ÜÞÜÓÒzٯٯٯ wÓ ÜÑ ÜÀ. .
+í<µwÜÑwÒs . . . . ¬á¶¡ eÐbðà à;Òz ! ! !A.A
+ÓaÓaÓa AAAÙiA_A ´á È¡ÅÁz a·w Ãâiðà ÜÀaz
+¬éz à;Òz . . . . ´®º ÜÑ¡ ÜÞÜÂz ñgñbõIíüóéa»
+µÁ²¡Òz ! ! í<µwÜÑ à;w¡ Ùiê¾Å ´ôw¡w í<wÁÒz i´z
+ÜÞaA⠯Ρ®¡Òz ´á ñgñbõIíüóé¯Üïi´z!! ÜÀÜÀsÙ½ ÙbÙb*
+
diff --git a/Lib/test/cjkencodings/shift_jis-utf8.txt b/Lib/test/cjkencodings/shift_jis-utf8.txt
new file mode 100644
index 0000000..7763250
--- /dev/null
+++ b/Lib/test/cjkencodings/shift_jis-utf8.txt
@@ -0,0 +1,7 @@
+Python の開発は、1990 年ごろから開始されています。
+開発者の Guido van Rossum は教育用のプログラミング言語「ABC」の開発に参加していましたが、ABC は実用上の目的にはあまり適していませんでした。
+このため、Guido はより実用的なプログラミング言語の開発を開始し、英国 BBS 放送のコメディ番組「モンティ パイソン」のファンである Guido はこの言語を「Python」と名づけました。
+このような背景から生まれた Python の言語設計は、「シンプル」で「習得が容易」という目標に重点が置かれています。
+多くのスクリプト系言語ではユーザの目先の利便性を優先して色々な機能を言語要素として取り入れる場合が多いのですが、Python ではそういった小細工が追加されることはあまりありません。
+言語自体の機能は最小限に押さえ、必要な機能は拡張モジュールとして追加する、というのが Python のポリシーです。
+
diff --git a/Lib/test/cjkencodings/shift_jis.txt b/Lib/test/cjkencodings/shift_jis.txt
new file mode 100644
index 0000000..10b760d
--- /dev/null
+++ b/Lib/test/cjkencodings/shift_jis.txt
@@ -0,0 +1,7 @@
+Python ÌJÍA1990 N²ë©çJn³êĢܷB
+JÒÌ Guido van Rossum ͳçpÌvO~O¾êuABCvÌJÉQÁµÄ¢Üµ½ªAABC ÍÀpãÌÚIÉÍ ÜèKµÄ¢Ü¹ñŵ½B
+±Ì½ßAGuido ÍæèÀpIÈvO~O¾êÌJðJnµAp BBS úÌRfBÔgueB pC\vÌt@Å é Guido ͱ̾êðuPythonvƼïܵ½B
+±Ìæ¤Èwi©ç¶Üê½ Python ̾êÝvÍAuVvvÅuK¾ªeÕvÆ¢¤ÚWÉd_ªu©êĢܷB
+½ÌXNvgn¾êÅÍ[UÌÚæÌÖ«ðDæµÄFXÈ@\ð¾êvfÆµÄæèüêéꪽ¢ÌÅ·ªAPython ÅÍ»¤¢Á½¬×HªÇÁ³êé±ÆÍ Üè èܹñB
+¾ê©ÌÌ@\ÍŬÀɳ¦AKvÈ@\Íg£W
[ƵÄÇÁ·éAÆ¢¤Ìª Python Ì|V[Å·B
+
diff --git a/Lib/test/cjkencodings/shift_jisx0213-utf8.txt b/Lib/test/cjkencodings/shift_jisx0213-utf8.txt
new file mode 100644
index 0000000..9a56a2e
--- /dev/null
+++ b/Lib/test/cjkencodings/shift_jisx0213-utf8.txt
@@ -0,0 +1,8 @@
+Python の開発は、1990 年ごろから開始されています。
+開発者の Guido van Rossum は教育用のプログラミング言語「ABC」の開発に参加していましたが、ABC は実用上の目的にはあまり適していませんでした。
+このため、Guido はより実用的なプログラミング言語の開発を開始し、英国 BBS 放送のコメディ番組「モンティ パイソン」のファンである Guido はこの言語を「Python」と名づけました。
+このような背景から生まれた Python の言語設計は、「シンプル」で「習得が容易」という目標に重点が置かれています。
+多くのスクリプト系言語ではユーザの目先の利便性を優先して色々な機能を言語要素として取り入れる場合が多いのですが、Python ではそういった小細工が追加されることはあまりありません。
+言語自体の機能は最小限に押さえ、必要な機能は拡張モジュールとして追加する、というのが Python のポリシーです。
+
+ノか゚ ト゚ トキ喝塀 𡚴𪎌 麀齁𩛰
diff --git a/Lib/test/cjkencodings/shift_jisx0213.txt b/Lib/test/cjkencodings/shift_jisx0213.txt
new file mode 100644
index 0000000..08c9ef4
--- /dev/null
+++ b/Lib/test/cjkencodings/shift_jisx0213.txt
@@ -0,0 +1,8 @@
+Python ÌJÍA1990 N²ë©çJn³êĢܷB
+JÒÌ Guido van Rossum ͳçpÌvO~O¾êuABCvÌJÉQÁµÄ¢Üµ½ªAABC ÍÀpãÌÚIÉÍ ÜèKµÄ¢Ü¹ñŵ½B
+±Ì½ßAGuido ÍæèÀpIÈvO~O¾êÌJðJnµAp BBS úÌRfBÔgueB pC\vÌt@Å é Guido ͱ̾êðuPythonvƼïܵ½B
+±Ìæ¤Èwi©ç¶Üê½ Python ̾êÝvÍAuVvvÅuK¾ªeÕvÆ¢¤ÚWÉd_ªu©êĢܷB
+½ÌXNvgn¾êÅÍ[UÌÚæÌÖ«ðDæµÄFXÈ@\ð¾êvfÆµÄæèüêéꪽ¢ÌÅ·ªAPython ÅÍ»¤¢Á½¬×HªÇÁ³êé±ÆÍ Üè èܹñB
+¾ê©ÌÌ@\ÍŬÀɳ¦AKvÈ@\Íg£W
[ƵÄÇÁ·éAÆ¢¤Ìª Python Ì|V[Å·B
+
+mõ gLKy üÖ üÒüæûÔ
diff --git a/Lib/test/cjkencodings_test.py b/Lib/test/cjkencodings_test.py
deleted file mode 100644
index 31432d1..0000000
--- a/Lib/test/cjkencodings_test.py
+++ /dev/null
@@ -1,1019 +0,0 @@
-teststring = {
-'big5': (
-"\xa6\x70\xa6\xf3\xa6\x62\x20\x50\x79\x74\x68\x6f\x6e\x20\xa4\xa4"
-"\xa8\xcf\xa5\xce\xac\x4a\xa6\xb3\xaa\xba\x20\x43\x20\x6c\x69\x62"
-"\x72\x61\x72\x79\x3f\x0a\xa1\x40\xa6\x62\xb8\xea\xb0\x54\xac\xec"
-"\xa7\xde\xa7\xd6\xb3\x74\xb5\x6f\xae\x69\xaa\xba\xa4\xb5\xa4\xd1"
-"\x2c\x20\xb6\x7d\xb5\x6f\xa4\xce\xb4\xfa\xb8\xd5\xb3\x6e\xc5\xe9"
-"\xaa\xba\xb3\x74\xab\xd7\xac\x4f\xa4\xa3\xae\x65\xa9\xbf\xb5\xf8"
-"\xaa\xba\x0a\xbd\xd2\xc3\x44\x2e\x20\xac\xb0\xa5\x5b\xa7\xd6\xb6"
-"\x7d\xb5\x6f\xa4\xce\xb4\xfa\xb8\xd5\xaa\xba\xb3\x74\xab\xd7\x2c"
-"\x20\xa7\xda\xad\xcc\xab\x4b\xb1\x60\xa7\xc6\xb1\xe6\xaf\xe0\xa7"
-"\x51\xa5\xce\xa4\x40\xa8\xc7\xa4\x77\xb6\x7d\xb5\x6f\xa6\x6e\xaa"
-"\xba\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\xa8\xc3\xa6\xb3\xa4"
-"\x40\xad\xd3\x20\x66\x61\x73\x74\x20\x70\x72\x6f\x74\x6f\x74\x79"
-"\x70\x69\x6e\x67\x20\xaa\xba\x20\x70\x72\x6f\x67\x72\x61\x6d\x6d"
-"\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x20\xa5\x69\x0a"
-"\xa8\xd1\xa8\xcf\xa5\xce\x2e\x20\xa5\xd8\xab\x65\xa6\xb3\xb3\x5c"
-"\xb3\x5c\xa6\x68\xa6\x68\xaa\xba\x20\x6c\x69\x62\x72\x61\x72\x79"
-"\x20\xac\x4f\xa5\x48\x20\x43\x20\xbc\x67\xa6\xa8\x2c\x20\xa6\xd3"
-"\x20\x50\x79\x74\x68\x6f\x6e\x20\xac\x4f\xa4\x40\xad\xd3\x0a\x66"
-"\x61\x73\x74\x20\x70\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20"
-"\xaa\xba\x20\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c"
-"\x61\x6e\x67\x75\x61\x67\x65\x2e\x20\xac\x47\xa7\xda\xad\xcc\xa7"
-"\xc6\xb1\xe6\xaf\xe0\xb1\x4e\xac\x4a\xa6\xb3\xaa\xba\x0a\x43\x20"
-"\x6c\x69\x62\x72\x61\x72\x79\x20\xae\xb3\xa8\xec\x20\x50\x79\x74"
-"\x68\x6f\x6e\x20\xaa\xba\xc0\xf4\xb9\xd2\xa4\xa4\xb4\xfa\xb8\xd5"
-"\xa4\xce\xbe\xe3\xa6\x58\x2e\x20\xa8\xe4\xa4\xa4\xb3\xcc\xa5\x44"
-"\xad\x6e\xa4\x5d\xac\x4f\xa7\xda\xad\xcc\xa9\xd2\x0a\xad\x6e\xb0"
-"\x51\xbd\xd7\xaa\xba\xb0\xdd\xc3\x44\xb4\x4e\xac\x4f\x3a\x0a\x0a",
-"\xe5\xa6\x82\xe4\xbd\x95\xe5\x9c\xa8\x20\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe4\xb8\xad\xe4\xbd\xbf\xe7\x94\xa8\xe6\x97\xa2\xe6\x9c\x89"
-"\xe7\x9a\x84\x20\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x3f\x0a\xe3"
-"\x80\x80\xe5\x9c\xa8\xe8\xb3\x87\xe8\xa8\x8a\xe7\xa7\x91\xe6\x8a"
-"\x80\xe5\xbf\xab\xe9\x80\x9f\xe7\x99\xbc\xe5\xb1\x95\xe7\x9a\x84"
-"\xe4\xbb\x8a\xe5\xa4\xa9\x2c\x20\xe9\x96\x8b\xe7\x99\xbc\xe5\x8f"
-"\x8a\xe6\xb8\xac\xe8\xa9\xa6\xe8\xbb\x9f\xe9\xab\x94\xe7\x9a\x84"
-"\xe9\x80\x9f\xe5\xba\xa6\xe6\x98\xaf\xe4\xb8\x8d\xe5\xae\xb9\xe5"
-"\xbf\xbd\xe8\xa6\x96\xe7\x9a\x84\x0a\xe8\xaa\xb2\xe9\xa1\x8c\x2e"
-"\x20\xe7\x82\xba\xe5\x8a\xa0\xe5\xbf\xab\xe9\x96\x8b\xe7\x99\xbc"
-"\xe5\x8f\x8a\xe6\xb8\xac\xe8\xa9\xa6\xe7\x9a\x84\xe9\x80\x9f\xe5"
-"\xba\xa6\x2c\x20\xe6\x88\x91\xe5\x80\x91\xe4\xbe\xbf\xe5\xb8\xb8"
-"\xe5\xb8\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\x88\xa9\xe7\x94\xa8\xe4"
-"\xb8\x80\xe4\xba\x9b\xe5\xb7\xb2\xe9\x96\x8b\xe7\x99\xbc\xe5\xa5"
-"\xbd\xe7\x9a\x84\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\xe4\xb8"
-"\xa6\xe6\x9c\x89\xe4\xb8\x80\xe5\x80\x8b\x20\x66\x61\x73\x74\x20"
-"\x70\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20"
-"\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67"
-"\x75\x61\x67\x65\x20\xe5\x8f\xaf\x0a\xe4\xbe\x9b\xe4\xbd\xbf\xe7"
-"\x94\xa8\x2e\x20\xe7\x9b\xae\xe5\x89\x8d\xe6\x9c\x89\xe8\xa8\xb1"
-"\xe8\xa8\xb1\xe5\xa4\x9a\xe5\xa4\x9a\xe7\x9a\x84\x20\x6c\x69\x62"
-"\x72\x61\x72\x79\x20\xe6\x98\xaf\xe4\xbb\xa5\x20\x43\x20\xe5\xaf"
-"\xab\xe6\x88\x90\x2c\x20\xe8\x80\x8c\x20\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe6\x98\xaf\xe4\xb8\x80\xe5\x80\x8b\x0a\x66\x61\x73\x74\x20"
-"\x70\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20"
-"\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67"
-"\x75\x61\x67\x65\x2e\x20\xe6\x95\x85\xe6\x88\x91\xe5\x80\x91\xe5"
-"\xb8\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\xb0\x87\xe6\x97\xa2\xe6\x9c"
-"\x89\xe7\x9a\x84\x0a\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x20\xe6"
-"\x8b\xbf\xe5\x88\xb0\x20\x50\x79\x74\x68\x6f\x6e\x20\xe7\x9a\x84"
-"\xe7\x92\xb0\xe5\xa2\x83\xe4\xb8\xad\xe6\xb8\xac\xe8\xa9\xa6\xe5"
-"\x8f\x8a\xe6\x95\xb4\xe5\x90\x88\x2e\x20\xe5\x85\xb6\xe4\xb8\xad"
-"\xe6\x9c\x80\xe4\xb8\xbb\xe8\xa6\x81\xe4\xb9\x9f\xe6\x98\xaf\xe6"
-"\x88\x91\xe5\x80\x91\xe6\x89\x80\x0a\xe8\xa6\x81\xe8\xa8\x8e\xe8"
-"\xab\x96\xe7\x9a\x84\xe5\x95\x8f\xe9\xa1\x8c\xe5\xb0\xb1\xe6\x98"
-"\xaf\x3a\x0a\x0a"),
-'big5hkscs': (
-"\x88\x45\x88\x5c\x8a\x73\x8b\xda\x8d\xd8\x0a\x88\x66\x88\x62\x88"
-"\xa7\x20\x88\xa7\x88\xa3\x0a",
-"\xf0\xa0\x84\x8c\xc4\x9a\xe9\xb5\xae\xe7\xbd\x93\xe6\xb4\x86\x0a"
-"\xc3\x8a\xc3\x8a\xcc\x84\xc3\xaa\x20\xc3\xaa\xc3\xaa\xcc\x84\x0a"),
-'cp949': (
-"\x8c\x63\xb9\xe6\xb0\xa2\xc7\xcf\x20\xbc\x84\xbd\xc3\xc4\xdd\xb6"
-"\xf3\x0a\x0a\xa8\xc0\xa8\xc0\xb3\xb3\x21\x21\x20\xec\xd7\xce\xfa"
-"\xea\xc5\xc6\xd0\x92\xe6\x90\x70\xb1\xc5\x20\xa8\xde\xa8\xd3\xc4"
-"\x52\xa2\xaf\xa2\xaf\xa2\xaf\x20\xb1\xe0\x8a\x96\x20\xa8\xd1\xb5"
-"\xb3\x20\xa8\xc0\x2e\x20\x2e\x0a\xe4\xac\xbf\xb5\xa8\xd1\xb4\xc9"
-"\xc8\xc2\x20\x2e\x20\x2e\x20\x2e\x20\x2e\x20\xbc\xad\xbf\xef\xb7"
-"\xef\x20\xb5\xaf\xc7\xd0\xeb\xe0\x20\xca\xab\xc4\x52\x20\x21\x20"
-"\x21\x20\x21\xa4\xd0\x2e\xa4\xd0\x0a\xc8\xe5\xc8\xe5\xc8\xe5\x20"
-"\xa4\xa1\xa4\xa1\xa4\xa1\xa1\xd9\xa4\xd0\x5f\xa4\xd0\x20\xbe\xee"
-"\x90\x8a\x20\xc5\xcb\xc4\xe2\x83\x4f\x20\xb5\xae\xc0\xc0\x20\xaf"
-"\x68\xce\xfa\xb5\xe9\xeb\xe0\x20\xa8\xc0\xb5\xe5\x83\x4f\x0a\xbc"
-"\xb3\x90\x6a\x20\xca\xab\xc4\x52\x20\x2e\x20\x2e\x20\x2e\x20\x2e"
-"\x20\xb1\xbc\xbe\xd6\x9a\x66\x20\xa8\xd1\xb1\xc5\x20\xa8\xde\x90"
-"\x74\xa8\xc2\x83\x4f\x20\xec\xd7\xec\xd2\xf4\xb9\xe5\xfc\xf1\xe9"
-"\xb1\xee\xa3\x8e\x0a\xbf\xcd\xbe\xac\xc4\x52\x20\x21\x20\x21\x20"
-"\xe4\xac\xbf\xb5\xa8\xd1\x20\xca\xab\xb4\xc9\xb1\xc5\x20\xa1\xd9"
-"\xdf\xbe\xb0\xfc\x20\xbe\xf8\xb4\xc9\xb1\xc5\xb4\xc9\x20\xe4\xac"
-"\xb4\xc9\xb5\xd8\xc4\x52\x20\xb1\xdb\xbe\xd6\x8a\xdb\x0a\xa8\xde"
-"\xb7\xc1\xb5\xe0\xce\xfa\x20\x9a\xc3\xc7\xb4\xbd\xa4\xc4\x52\x20"
-"\xbe\xee\x90\x8a\x20\xec\xd7\xec\xd2\xf4\xb9\xe5\xfc\xf1\xe9\x9a"
-"\xc4\xa8\xef\xb5\xe9\x9d\xda\x21\x21\x20\xa8\xc0\xa8\xc0\xb3\xb3"
-"\xa2\xbd\x20\xa1\xd2\xa1\xd2\x2a\x0a\x0a",
-"\xeb\x98\xa0\xeb\xb0\xa9\xea\xb0\x81\xed\x95\x98\x20\xed\x8e\xb2"
-"\xec\x8b\x9c\xec\xbd\x9c\xeb\x9d\xbc\x0a\x0a\xe3\x89\xaf\xe3\x89"
-"\xaf\xeb\x82\xa9\x21\x21\x20\xe5\x9b\xa0\xe4\xb9\x9d\xe6\x9c\x88"
-"\xed\x8c\xa8\xeb\xaf\xa4\xeb\xa6\x94\xea\xb6\x88\x20\xe2\x93\xa1"
-"\xe2\x93\x96\xed\x9b\x80\xc2\xbf\xc2\xbf\xc2\xbf\x20\xea\xb8\x8d"
-"\xeb\x92\x99\x20\xe2\x93\x94\xeb\x8e\xa8\x20\xe3\x89\xaf\x2e\x20"
-"\x2e\x0a\xe4\xba\x9e\xec\x98\x81\xe2\x93\x94\xeb\x8a\xa5\xed\x9a"
-"\xb9\x20\x2e\x20\x2e\x20\x2e\x20\x2e\x20\xec\x84\x9c\xec\x9a\xb8"
-"\xeb\xa4\x84\x20\xeb\x8e\x90\xed\x95\x99\xe4\xb9\x99\x20\xe5\xae"
-"\xb6\xed\x9b\x80\x20\x21\x20\x21\x20\x21\xe3\x85\xa0\x2e\xe3\x85"
-"\xa0\x0a\xed\x9d\x90\xed\x9d\x90\xed\x9d\x90\x20\xe3\x84\xb1\xe3"
-"\x84\xb1\xe3\x84\xb1\xe2\x98\x86\xe3\x85\xa0\x5f\xe3\x85\xa0\x20"
-"\xec\x96\xb4\xeb\xa6\xa8\x20\xed\x83\xb8\xec\xbd\xb0\xea\xb8\x90"
-"\x20\xeb\x8e\x8c\xec\x9d\x91\x20\xec\xb9\x91\xe4\xb9\x9d\xeb\x93"
-"\xa4\xe4\xb9\x99\x20\xe3\x89\xaf\xeb\x93\x9c\xea\xb8\x90\x0a\xec"
-"\x84\xa4\xeb\xa6\x8c\x20\xe5\xae\xb6\xed\x9b\x80\x20\x2e\x20\x2e"
-"\x20\x2e\x20\x2e\x20\xea\xb5\xb4\xec\x95\xa0\xec\x89\x8c\x20\xe2"
-"\x93\x94\xea\xb6\x88\x20\xe2\x93\xa1\xeb\xa6\x98\xe3\x89\xb1\xea"
-"\xb8\x90\x20\xe5\x9b\xa0\xe4\xbb\x81\xe5\xb7\x9d\xef\xa6\x81\xe4"
-"\xb8\xad\xea\xb9\x8c\xec\xa6\xbc\x0a\xec\x99\x80\xec\x92\x80\xed"
-"\x9b\x80\x20\x21\x20\x21\x20\xe4\xba\x9e\xec\x98\x81\xe2\x93\x94"
-"\x20\xe5\xae\xb6\xeb\x8a\xa5\xea\xb6\x88\x20\xe2\x98\x86\xe4\xb8"
-"\x8a\xea\xb4\x80\x20\xec\x97\x86\xeb\x8a\xa5\xea\xb6\x88\xeb\x8a"
-"\xa5\x20\xe4\xba\x9e\xeb\x8a\xa5\xeb\x92\x88\xed\x9b\x80\x20\xea"
-"\xb8\x80\xec\x95\xa0\xeb\x93\xb4\x0a\xe2\x93\xa1\xeb\xa0\xa4\xeb"
-"\x93\x80\xe4\xb9\x9d\x20\xec\x8b\x80\xed\x92\x94\xec\x88\xb4\xed"
-"\x9b\x80\x20\xec\x96\xb4\xeb\xa6\xa8\x20\xe5\x9b\xa0\xe4\xbb\x81"
-"\xe5\xb7\x9d\xef\xa6\x81\xe4\xb8\xad\xec\x8b\x81\xe2\x91\xa8\xeb"
-"\x93\xa4\xec\x95\x9c\x21\x21\x20\xe3\x89\xaf\xe3\x89\xaf\xeb\x82"
-"\xa9\xe2\x99\xa1\x20\xe2\x8c\x92\xe2\x8c\x92\x2a\x0a\x0a"),
-'euc_jisx0213': (
-"\x50\x79\x74\x68\x6f\x6e\x20\xa4\xce\xb3\xab\xc8\xaf\xa4\xcf\xa1"
-"\xa2\x31\x39\x39\x30\x20\xc7\xaf\xa4\xb4\xa4\xed\xa4\xab\xa4\xe9"
-"\xb3\xab\xbb\xcf\xa4\xb5\xa4\xec\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9"
-"\xa1\xa3\x0a\xb3\xab\xc8\xaf\xbc\xd4\xa4\xce\x20\x47\x75\x69\x64"
-"\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73\x73\x75\x6d\x20\xa4\xcf\xb6"
-"\xb5\xb0\xe9\xcd\xd1\xa4\xce\xa5\xd7\xa5\xed\xa5\xb0\xa5\xe9\xa5"
-"\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec\xa1\xd6\x41\x42\x43\xa1\xd7"
-"\xa4\xce\xb3\xab\xc8\xaf\xa4\xcb\xbb\xb2\xb2\xc3\xa4\xb7\xa4\xc6"
-"\xa4\xa4\xa4\xde\xa4\xb7\xa4\xbf\xa4\xac\xa1\xa2\x41\x42\x43\x20"
-"\xa4\xcf\xbc\xc2\xcd\xd1\xbe\xe5\xa4\xce\xcc\xdc\xc5\xaa\xa4\xcb"
-"\xa4\xcf\xa4\xa2\xa4\xde\xa4\xea\xc5\xac\xa4\xb7\xa4\xc6\xa4\xa4"
-"\xa4\xde\xa4\xbb\xa4\xf3\xa4\xc7\xa4\xb7\xa4\xbf\xa1\xa3\x0a\xa4"
-"\xb3\xa4\xce\xa4\xbf\xa4\xe1\xa1\xa2\x47\x75\x69\x64\x6f\x20\xa4"
-"\xcf\xa4\xe8\xa4\xea\xbc\xc2\xcd\xd1\xc5\xaa\xa4\xca\xa5\xd7\xa5"
-"\xed\xa5\xb0\xa5\xe9\xa5\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec\xa4"
-"\xce\xb3\xab\xc8\xaf\xa4\xf2\xb3\xab\xbb\xcf\xa4\xb7\xa1\xa2\xb1"
-"\xd1\xb9\xf1\x20\x42\x42\x53\x20\xca\xfc\xc1\xf7\xa4\xce\xa5\xb3"
-"\xa5\xe1\xa5\xc7\xa5\xa3\xc8\xd6\xc1\xc8\xa1\xd6\xa5\xe2\xa5\xf3"
-"\xa5\xc6\xa5\xa3\x20\xa5\xd1\xa5\xa4\xa5\xbd\xa5\xf3\xa1\xd7\xa4"
-"\xce\xa5\xd5\xa5\xa1\xa5\xf3\xa4\xc7\xa4\xa2\xa4\xeb\x20\x47\x75"
-"\x69\x64\x6f\x20\xa4\xcf\xa4\xb3\xa4\xce\xb8\xc0\xb8\xec\xa4\xf2"
-"\xa1\xd6\x50\x79\x74\x68\x6f\x6e\xa1\xd7\xa4\xc8\xcc\xbe\xa4\xc5"
-"\xa4\xb1\xa4\xde\xa4\xb7\xa4\xbf\xa1\xa3\x0a\xa4\xb3\xa4\xce\xa4"
-"\xe8\xa4\xa6\xa4\xca\xc7\xd8\xb7\xca\xa4\xab\xa4\xe9\xc0\xb8\xa4"
-"\xde\xa4\xec\xa4\xbf\x20\x50\x79\x74\x68\x6f\x6e\x20\xa4\xce\xb8"
-"\xc0\xb8\xec\xc0\xdf\xb7\xd7\xa4\xcf\xa1\xa2\xa1\xd6\xa5\xb7\xa5"
-"\xf3\xa5\xd7\xa5\xeb\xa1\xd7\xa4\xc7\xa1\xd6\xbd\xac\xc6\xc0\xa4"
-"\xac\xcd\xc6\xb0\xd7\xa1\xd7\xa4\xc8\xa4\xa4\xa4\xa6\xcc\xdc\xc9"
-"\xb8\xa4\xcb\xbd\xc5\xc5\xc0\xa4\xac\xc3\xd6\xa4\xab\xa4\xec\xa4"
-"\xc6\xa4\xa4\xa4\xde\xa4\xb9\xa1\xa3\x0a\xc2\xbf\xa4\xaf\xa4\xce"
-"\xa5\xb9\xa5\xaf\xa5\xea\xa5\xd7\xa5\xc8\xb7\xcf\xb8\xc0\xb8\xec"
-"\xa4\xc7\xa4\xcf\xa5\xe6\xa1\xbc\xa5\xb6\xa4\xce\xcc\xdc\xc0\xe8"
-"\xa4\xce\xcd\xf8\xca\xd8\xc0\xad\xa4\xf2\xcd\xa5\xc0\xe8\xa4\xb7"
-"\xa4\xc6\xbf\xa7\xa1\xb9\xa4\xca\xb5\xa1\xc7\xbd\xa4\xf2\xb8\xc0"
-"\xb8\xec\xcd\xd7\xc1\xc7\xa4\xc8\xa4\xb7\xa4\xc6\xbc\xe8\xa4\xea"
-"\xc6\xfe\xa4\xec\xa4\xeb\xbe\xec\xb9\xe7\xa4\xac\xc2\xbf\xa4\xa4"
-"\xa4\xce\xa4\xc7\xa4\xb9\xa4\xac\xa1\xa2\x50\x79\x74\x68\x6f\x6e"
-"\x20\xa4\xc7\xa4\xcf\xa4\xbd\xa4\xa6\xa4\xa4\xa4\xc3\xa4\xbf\xbe"
-"\xae\xba\xd9\xb9\xa9\xa4\xac\xc4\xc9\xb2\xc3\xa4\xb5\xa4\xec\xa4"
-"\xeb\xa4\xb3\xa4\xc8\xa4\xcf\xa4\xa2\xa4\xde\xa4\xea\xa4\xa2\xa4"
-"\xea\xa4\xde\xa4\xbb\xa4\xf3\xa1\xa3\x0a\xb8\xc0\xb8\xec\xbc\xab"
-"\xc2\xce\xa4\xce\xb5\xa1\xc7\xbd\xa4\xcf\xba\xc7\xbe\xae\xb8\xc2"
-"\xa4\xcb\xb2\xa1\xa4\xb5\xa4\xa8\xa1\xa2\xc9\xac\xcd\xd7\xa4\xca"
-"\xb5\xa1\xc7\xbd\xa4\xcf\xb3\xc8\xc4\xa5\xa5\xe2\xa5\xb8\xa5\xe5"
-"\xa1\xbc\xa5\xeb\xa4\xc8\xa4\xb7\xa4\xc6\xc4\xc9\xb2\xc3\xa4\xb9"
-"\xa4\xeb\xa1\xa2\xa4\xc8\xa4\xa4\xa4\xa6\xa4\xce\xa4\xac\x20\x50"
-"\x79\x74\x68\x6f\x6e\x20\xa4\xce\xa5\xdd\xa5\xea\xa5\xb7\xa1\xbc"
-"\xa4\xc7\xa4\xb9\xa1\xa3\x0a\x0a\xa5\xce\xa4\xf7\x20\xa5\xfe\x20"
-"\xa5\xc8\xa5\xad\xaf\xac\xaf\xda\x20\xcf\xe3\x8f\xfe\xd8\x20\x8f"
-"\xfe\xd4\x8f\xfe\xe8\x8f\xfc\xd6\x0a",
-"\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xaf\xe3\x80\x81\x31\x39\x39\x30\x20\xe5\xb9\xb4\xe3\x81"
-"\x94\xe3\x82\x8d\xe3\x81\x8b\xe3\x82\x89\xe9\x96\x8b\xe5\xa7\x8b"
-"\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3"
-"\x81\x99\xe3\x80\x82\x0a\xe9\x96\x8b\xe7\x99\xba\xe8\x80\x85\xe3"
-"\x81\xae\x20\x47\x75\x69\x64\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73"
-"\x73\x75\x6d\x20\xe3\x81\xaf\xe6\x95\x99\xe8\x82\xb2\xe7\x94\xa8"
-"\xe3\x81\xae\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3"
-"\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e\xe3\x80"
-"\x8c\x41\x42\x43\xe3\x80\x8d\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xab\xe5\x8f\x82\xe5\x8a\xa0\xe3\x81\x97\xe3\x81\xa6\xe3"
-"\x81\x84\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x81\x8c\xe3\x80"
-"\x81\x41\x42\x43\x20\xe3\x81\xaf\xe5\xae\x9f\xe7\x94\xa8\xe4\xb8"
-"\x8a\xe3\x81\xae\xe7\x9b\xae\xe7\x9a\x84\xe3\x81\xab\xe3\x81\xaf"
-"\xe3\x81\x82\xe3\x81\xbe\xe3\x82\x8a\xe9\x81\xa9\xe3\x81\x97\xe3"
-"\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x81"
-"\xa7\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a\xe3\x81\x93\xe3\x81"
-"\xae\xe3\x81\x9f\xe3\x82\x81\xe3\x80\x81\x47\x75\x69\x64\x6f\x20"
-"\xe3\x81\xaf\xe3\x82\x88\xe3\x82\x8a\xe5\xae\x9f\xe7\x94\xa8\xe7"
-"\x9a\x84\xe3\x81\xaa\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83"
-"\xa9\xe3\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e"
-"\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba\xe3\x82\x92\xe9\x96\x8b\xe5"
-"\xa7\x8b\xe3\x81\x97\xe3\x80\x81\xe8\x8b\xb1\xe5\x9b\xbd\x20\x42"
-"\x42\x53\x20\xe6\x94\xbe\xe9\x80\x81\xe3\x81\xae\xe3\x82\xb3\xe3"
-"\x83\xa1\xe3\x83\x87\xe3\x82\xa3\xe7\x95\xaa\xe7\xb5\x84\xe3\x80"
-"\x8c\xe3\x83\xa2\xe3\x83\xb3\xe3\x83\x86\xe3\x82\xa3\x20\xe3\x83"
-"\x91\xe3\x82\xa4\xe3\x82\xbd\xe3\x83\xb3\xe3\x80\x8d\xe3\x81\xae"
-"\xe3\x83\x95\xe3\x82\xa1\xe3\x83\xb3\xe3\x81\xa7\xe3\x81\x82\xe3"
-"\x82\x8b\x20\x47\x75\x69\x64\x6f\x20\xe3\x81\xaf\xe3\x81\x93\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe3\x82\x92\xe3\x80\x8c\x50\x79"
-"\x74\x68\x6f\x6e\xe3\x80\x8d\xe3\x81\xa8\xe5\x90\x8d\xe3\x81\xa5"
-"\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a"
-"\xe3\x81\x93\xe3\x81\xae\xe3\x82\x88\xe3\x81\x86\xe3\x81\xaa\xe8"
-"\x83\x8c\xe6\x99\xaf\xe3\x81\x8b\xe3\x82\x89\xe7\x94\x9f\xe3\x81"
-"\xbe\xe3\x82\x8c\xe3\x81\x9f\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa8\xad\xe8\xa8\x88\xe3\x81"
-"\xaf\xe3\x80\x81\xe3\x80\x8c\xe3\x82\xb7\xe3\x83\xb3\xe3\x83\x97"
-"\xe3\x83\xab\xe3\x80\x8d\xe3\x81\xa7\xe3\x80\x8c\xe7\xbf\x92\xe5"
-"\xbe\x97\xe3\x81\x8c\xe5\xae\xb9\xe6\x98\x93\xe3\x80\x8d\xe3\x81"
-"\xa8\xe3\x81\x84\xe3\x81\x86\xe7\x9b\xae\xe6\xa8\x99\xe3\x81\xab"
-"\xe9\x87\x8d\xe7\x82\xb9\xe3\x81\x8c\xe7\xbd\xae\xe3\x81\x8b\xe3"
-"\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80"
-"\x82\x0a\xe5\xa4\x9a\xe3\x81\x8f\xe3\x81\xae\xe3\x82\xb9\xe3\x82"
-"\xaf\xe3\x83\xaa\xe3\x83\x97\xe3\x83\x88\xe7\xb3\xbb\xe8\xa8\x80"
-"\xe8\xaa\x9e\xe3\x81\xa7\xe3\x81\xaf\xe3\x83\xa6\xe3\x83\xbc\xe3"
-"\x82\xb6\xe3\x81\xae\xe7\x9b\xae\xe5\x85\x88\xe3\x81\xae\xe5\x88"
-"\xa9\xe4\xbe\xbf\xe6\x80\xa7\xe3\x82\x92\xe5\x84\xaa\xe5\x85\x88"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\x89\xb2\xe3\x80\x85\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x82\x92\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa6"
-"\x81\xe7\xb4\xa0\xe3\x81\xa8\xe3\x81\x97\xe3\x81\xa6\xe5\x8f\x96"
-"\xe3\x82\x8a\xe5\x85\xa5\xe3\x82\x8c\xe3\x82\x8b\xe5\xa0\xb4\xe5"
-"\x90\x88\xe3\x81\x8c\xe5\xa4\x9a\xe3\x81\x84\xe3\x81\xae\xe3\x81"
-"\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe3\x81\xa7\xe3\x81\xaf\xe3\x81\x9d\xe3\x81\x86\xe3\x81\x84"
-"\xe3\x81\xa3\xe3\x81\x9f\xe5\xb0\x8f\xe7\xb4\xb0\xe5\xb7\xa5\xe3"
-"\x81\x8c\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x95\xe3\x82\x8c\xe3\x82"
-"\x8b\xe3\x81\x93\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\x82\xe3\x81\xbe"
-"\xe3\x82\x8a\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3"
-"\x82\x93\xe3\x80\x82\x0a\xe8\xa8\x80\xe8\xaa\x9e\xe8\x87\xaa\xe4"
-"\xbd\x93\xe3\x81\xae\xe6\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x9c"
-"\x80\xe5\xb0\x8f\xe9\x99\x90\xe3\x81\xab\xe6\x8a\xbc\xe3\x81\x95"
-"\xe3\x81\x88\xe3\x80\x81\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x8b\xa1\xe5\xbc\xb5\xe3\x83"
-"\xa2\xe3\x82\xb8\xe3\x83\xa5\xe3\x83\xbc\xe3\x83\xab\xe3\x81\xa8"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x99\xe3"
-"\x82\x8b\xe3\x80\x81\xe3\x81\xa8\xe3\x81\x84\xe3\x81\x86\xe3\x81"
-"\xae\xe3\x81\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe3"
-"\x83\x9d\xe3\x83\xaa\xe3\x82\xb7\xe3\x83\xbc\xe3\x81\xa7\xe3\x81"
-"\x99\xe3\x80\x82\x0a\x0a\xe3\x83\x8e\xe3\x81\x8b\xe3\x82\x9a\x20"
-"\xe3\x83\x88\xe3\x82\x9a\x20\xe3\x83\x88\xe3\x82\xad\xef\xa8\xb6"
-"\xef\xa8\xb9\x20\xf0\xa1\x9a\xb4\xf0\xaa\x8e\x8c\x20\xe9\xba\x80"
-"\xe9\xbd\x81\xf0\xa9\x9b\xb0\x0a"),
-'euc_jp': (
-"\x50\x79\x74\x68\x6f\x6e\x20\xa4\xce\xb3\xab\xc8\xaf\xa4\xcf\xa1"
-"\xa2\x31\x39\x39\x30\x20\xc7\xaf\xa4\xb4\xa4\xed\xa4\xab\xa4\xe9"
-"\xb3\xab\xbb\xcf\xa4\xb5\xa4\xec\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9"
-"\xa1\xa3\x0a\xb3\xab\xc8\xaf\xbc\xd4\xa4\xce\x20\x47\x75\x69\x64"
-"\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73\x73\x75\x6d\x20\xa4\xcf\xb6"
-"\xb5\xb0\xe9\xcd\xd1\xa4\xce\xa5\xd7\xa5\xed\xa5\xb0\xa5\xe9\xa5"
-"\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec\xa1\xd6\x41\x42\x43\xa1\xd7"
-"\xa4\xce\xb3\xab\xc8\xaf\xa4\xcb\xbb\xb2\xb2\xc3\xa4\xb7\xa4\xc6"
-"\xa4\xa4\xa4\xde\xa4\xb7\xa4\xbf\xa4\xac\xa1\xa2\x41\x42\x43\x20"
-"\xa4\xcf\xbc\xc2\xcd\xd1\xbe\xe5\xa4\xce\xcc\xdc\xc5\xaa\xa4\xcb"
-"\xa4\xcf\xa4\xa2\xa4\xde\xa4\xea\xc5\xac\xa4\xb7\xa4\xc6\xa4\xa4"
-"\xa4\xde\xa4\xbb\xa4\xf3\xa4\xc7\xa4\xb7\xa4\xbf\xa1\xa3\x0a\xa4"
-"\xb3\xa4\xce\xa4\xbf\xa4\xe1\xa1\xa2\x47\x75\x69\x64\x6f\x20\xa4"
-"\xcf\xa4\xe8\xa4\xea\xbc\xc2\xcd\xd1\xc5\xaa\xa4\xca\xa5\xd7\xa5"
-"\xed\xa5\xb0\xa5\xe9\xa5\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec\xa4"
-"\xce\xb3\xab\xc8\xaf\xa4\xf2\xb3\xab\xbb\xcf\xa4\xb7\xa1\xa2\xb1"
-"\xd1\xb9\xf1\x20\x42\x42\x53\x20\xca\xfc\xc1\xf7\xa4\xce\xa5\xb3"
-"\xa5\xe1\xa5\xc7\xa5\xa3\xc8\xd6\xc1\xc8\xa1\xd6\xa5\xe2\xa5\xf3"
-"\xa5\xc6\xa5\xa3\x20\xa5\xd1\xa5\xa4\xa5\xbd\xa5\xf3\xa1\xd7\xa4"
-"\xce\xa5\xd5\xa5\xa1\xa5\xf3\xa4\xc7\xa4\xa2\xa4\xeb\x20\x47\x75"
-"\x69\x64\x6f\x20\xa4\xcf\xa4\xb3\xa4\xce\xb8\xc0\xb8\xec\xa4\xf2"
-"\xa1\xd6\x50\x79\x74\x68\x6f\x6e\xa1\xd7\xa4\xc8\xcc\xbe\xa4\xc5"
-"\xa4\xb1\xa4\xde\xa4\xb7\xa4\xbf\xa1\xa3\x0a\xa4\xb3\xa4\xce\xa4"
-"\xe8\xa4\xa6\xa4\xca\xc7\xd8\xb7\xca\xa4\xab\xa4\xe9\xc0\xb8\xa4"
-"\xde\xa4\xec\xa4\xbf\x20\x50\x79\x74\x68\x6f\x6e\x20\xa4\xce\xb8"
-"\xc0\xb8\xec\xc0\xdf\xb7\xd7\xa4\xcf\xa1\xa2\xa1\xd6\xa5\xb7\xa5"
-"\xf3\xa5\xd7\xa5\xeb\xa1\xd7\xa4\xc7\xa1\xd6\xbd\xac\xc6\xc0\xa4"
-"\xac\xcd\xc6\xb0\xd7\xa1\xd7\xa4\xc8\xa4\xa4\xa4\xa6\xcc\xdc\xc9"
-"\xb8\xa4\xcb\xbd\xc5\xc5\xc0\xa4\xac\xc3\xd6\xa4\xab\xa4\xec\xa4"
-"\xc6\xa4\xa4\xa4\xde\xa4\xb9\xa1\xa3\x0a\xc2\xbf\xa4\xaf\xa4\xce"
-"\xa5\xb9\xa5\xaf\xa5\xea\xa5\xd7\xa5\xc8\xb7\xcf\xb8\xc0\xb8\xec"
-"\xa4\xc7\xa4\xcf\xa5\xe6\xa1\xbc\xa5\xb6\xa4\xce\xcc\xdc\xc0\xe8"
-"\xa4\xce\xcd\xf8\xca\xd8\xc0\xad\xa4\xf2\xcd\xa5\xc0\xe8\xa4\xb7"
-"\xa4\xc6\xbf\xa7\xa1\xb9\xa4\xca\xb5\xa1\xc7\xbd\xa4\xf2\xb8\xc0"
-"\xb8\xec\xcd\xd7\xc1\xc7\xa4\xc8\xa4\xb7\xa4\xc6\xbc\xe8\xa4\xea"
-"\xc6\xfe\xa4\xec\xa4\xeb\xbe\xec\xb9\xe7\xa4\xac\xc2\xbf\xa4\xa4"
-"\xa4\xce\xa4\xc7\xa4\xb9\xa4\xac\xa1\xa2\x50\x79\x74\x68\x6f\x6e"
-"\x20\xa4\xc7\xa4\xcf\xa4\xbd\xa4\xa6\xa4\xa4\xa4\xc3\xa4\xbf\xbe"
-"\xae\xba\xd9\xb9\xa9\xa4\xac\xc4\xc9\xb2\xc3\xa4\xb5\xa4\xec\xa4"
-"\xeb\xa4\xb3\xa4\xc8\xa4\xcf\xa4\xa2\xa4\xde\xa4\xea\xa4\xa2\xa4"
-"\xea\xa4\xde\xa4\xbb\xa4\xf3\xa1\xa3\x0a\xb8\xc0\xb8\xec\xbc\xab"
-"\xc2\xce\xa4\xce\xb5\xa1\xc7\xbd\xa4\xcf\xba\xc7\xbe\xae\xb8\xc2"
-"\xa4\xcb\xb2\xa1\xa4\xb5\xa4\xa8\xa1\xa2\xc9\xac\xcd\xd7\xa4\xca"
-"\xb5\xa1\xc7\xbd\xa4\xcf\xb3\xc8\xc4\xa5\xa5\xe2\xa5\xb8\xa5\xe5"
-"\xa1\xbc\xa5\xeb\xa4\xc8\xa4\xb7\xa4\xc6\xc4\xc9\xb2\xc3\xa4\xb9"
-"\xa4\xeb\xa1\xa2\xa4\xc8\xa4\xa4\xa4\xa6\xa4\xce\xa4\xac\x20\x50"
-"\x79\x74\x68\x6f\x6e\x20\xa4\xce\xa5\xdd\xa5\xea\xa5\xb7\xa1\xbc"
-"\xa4\xc7\xa4\xb9\xa1\xa3\x0a\x0a",
-"\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xaf\xe3\x80\x81\x31\x39\x39\x30\x20\xe5\xb9\xb4\xe3\x81"
-"\x94\xe3\x82\x8d\xe3\x81\x8b\xe3\x82\x89\xe9\x96\x8b\xe5\xa7\x8b"
-"\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3"
-"\x81\x99\xe3\x80\x82\x0a\xe9\x96\x8b\xe7\x99\xba\xe8\x80\x85\xe3"
-"\x81\xae\x20\x47\x75\x69\x64\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73"
-"\x73\x75\x6d\x20\xe3\x81\xaf\xe6\x95\x99\xe8\x82\xb2\xe7\x94\xa8"
-"\xe3\x81\xae\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3"
-"\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e\xe3\x80"
-"\x8c\x41\x42\x43\xe3\x80\x8d\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xab\xe5\x8f\x82\xe5\x8a\xa0\xe3\x81\x97\xe3\x81\xa6\xe3"
-"\x81\x84\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x81\x8c\xe3\x80"
-"\x81\x41\x42\x43\x20\xe3\x81\xaf\xe5\xae\x9f\xe7\x94\xa8\xe4\xb8"
-"\x8a\xe3\x81\xae\xe7\x9b\xae\xe7\x9a\x84\xe3\x81\xab\xe3\x81\xaf"
-"\xe3\x81\x82\xe3\x81\xbe\xe3\x82\x8a\xe9\x81\xa9\xe3\x81\x97\xe3"
-"\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x81"
-"\xa7\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a\xe3\x81\x93\xe3\x81"
-"\xae\xe3\x81\x9f\xe3\x82\x81\xe3\x80\x81\x47\x75\x69\x64\x6f\x20"
-"\xe3\x81\xaf\xe3\x82\x88\xe3\x82\x8a\xe5\xae\x9f\xe7\x94\xa8\xe7"
-"\x9a\x84\xe3\x81\xaa\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83"
-"\xa9\xe3\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e"
-"\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba\xe3\x82\x92\xe9\x96\x8b\xe5"
-"\xa7\x8b\xe3\x81\x97\xe3\x80\x81\xe8\x8b\xb1\xe5\x9b\xbd\x20\x42"
-"\x42\x53\x20\xe6\x94\xbe\xe9\x80\x81\xe3\x81\xae\xe3\x82\xb3\xe3"
-"\x83\xa1\xe3\x83\x87\xe3\x82\xa3\xe7\x95\xaa\xe7\xb5\x84\xe3\x80"
-"\x8c\xe3\x83\xa2\xe3\x83\xb3\xe3\x83\x86\xe3\x82\xa3\x20\xe3\x83"
-"\x91\xe3\x82\xa4\xe3\x82\xbd\xe3\x83\xb3\xe3\x80\x8d\xe3\x81\xae"
-"\xe3\x83\x95\xe3\x82\xa1\xe3\x83\xb3\xe3\x81\xa7\xe3\x81\x82\xe3"
-"\x82\x8b\x20\x47\x75\x69\x64\x6f\x20\xe3\x81\xaf\xe3\x81\x93\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe3\x82\x92\xe3\x80\x8c\x50\x79"
-"\x74\x68\x6f\x6e\xe3\x80\x8d\xe3\x81\xa8\xe5\x90\x8d\xe3\x81\xa5"
-"\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a"
-"\xe3\x81\x93\xe3\x81\xae\xe3\x82\x88\xe3\x81\x86\xe3\x81\xaa\xe8"
-"\x83\x8c\xe6\x99\xaf\xe3\x81\x8b\xe3\x82\x89\xe7\x94\x9f\xe3\x81"
-"\xbe\xe3\x82\x8c\xe3\x81\x9f\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa8\xad\xe8\xa8\x88\xe3\x81"
-"\xaf\xe3\x80\x81\xe3\x80\x8c\xe3\x82\xb7\xe3\x83\xb3\xe3\x83\x97"
-"\xe3\x83\xab\xe3\x80\x8d\xe3\x81\xa7\xe3\x80\x8c\xe7\xbf\x92\xe5"
-"\xbe\x97\xe3\x81\x8c\xe5\xae\xb9\xe6\x98\x93\xe3\x80\x8d\xe3\x81"
-"\xa8\xe3\x81\x84\xe3\x81\x86\xe7\x9b\xae\xe6\xa8\x99\xe3\x81\xab"
-"\xe9\x87\x8d\xe7\x82\xb9\xe3\x81\x8c\xe7\xbd\xae\xe3\x81\x8b\xe3"
-"\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80"
-"\x82\x0a\xe5\xa4\x9a\xe3\x81\x8f\xe3\x81\xae\xe3\x82\xb9\xe3\x82"
-"\xaf\xe3\x83\xaa\xe3\x83\x97\xe3\x83\x88\xe7\xb3\xbb\xe8\xa8\x80"
-"\xe8\xaa\x9e\xe3\x81\xa7\xe3\x81\xaf\xe3\x83\xa6\xe3\x83\xbc\xe3"
-"\x82\xb6\xe3\x81\xae\xe7\x9b\xae\xe5\x85\x88\xe3\x81\xae\xe5\x88"
-"\xa9\xe4\xbe\xbf\xe6\x80\xa7\xe3\x82\x92\xe5\x84\xaa\xe5\x85\x88"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\x89\xb2\xe3\x80\x85\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x82\x92\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa6"
-"\x81\xe7\xb4\xa0\xe3\x81\xa8\xe3\x81\x97\xe3\x81\xa6\xe5\x8f\x96"
-"\xe3\x82\x8a\xe5\x85\xa5\xe3\x82\x8c\xe3\x82\x8b\xe5\xa0\xb4\xe5"
-"\x90\x88\xe3\x81\x8c\xe5\xa4\x9a\xe3\x81\x84\xe3\x81\xae\xe3\x81"
-"\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe3\x81\xa7\xe3\x81\xaf\xe3\x81\x9d\xe3\x81\x86\xe3\x81\x84"
-"\xe3\x81\xa3\xe3\x81\x9f\xe5\xb0\x8f\xe7\xb4\xb0\xe5\xb7\xa5\xe3"
-"\x81\x8c\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x95\xe3\x82\x8c\xe3\x82"
-"\x8b\xe3\x81\x93\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\x82\xe3\x81\xbe"
-"\xe3\x82\x8a\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3"
-"\x82\x93\xe3\x80\x82\x0a\xe8\xa8\x80\xe8\xaa\x9e\xe8\x87\xaa\xe4"
-"\xbd\x93\xe3\x81\xae\xe6\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x9c"
-"\x80\xe5\xb0\x8f\xe9\x99\x90\xe3\x81\xab\xe6\x8a\xbc\xe3\x81\x95"
-"\xe3\x81\x88\xe3\x80\x81\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x8b\xa1\xe5\xbc\xb5\xe3\x83"
-"\xa2\xe3\x82\xb8\xe3\x83\xa5\xe3\x83\xbc\xe3\x83\xab\xe3\x81\xa8"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x99\xe3"
-"\x82\x8b\xe3\x80\x81\xe3\x81\xa8\xe3\x81\x84\xe3\x81\x86\xe3\x81"
-"\xae\xe3\x81\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe3"
-"\x83\x9d\xe3\x83\xaa\xe3\x82\xb7\xe3\x83\xbc\xe3\x81\xa7\xe3\x81"
-"\x99\xe3\x80\x82\x0a\x0a"),
-'euc_kr': (
-"\xa1\xdd\x20\xc6\xc4\xc0\xcc\xbd\xe3\x28\x50\x79\x74\x68\x6f\x6e"
-"\x29\xc0\xba\x20\xb9\xe8\xbf\xec\xb1\xe2\x20\xbd\xb1\xb0\xed\x2c"
-"\x20\xb0\xad\xb7\xc2\xc7\xd1\x20\xc7\xc1\xb7\xce\xb1\xd7\xb7\xa1"
-"\xb9\xd6\x20\xbe\xf0\xbe\xee\xc0\xd4\xb4\xcf\xb4\xd9\x2e\x20\xc6"
-"\xc4\xc0\xcc\xbd\xe3\xc0\xba\x0a\xc8\xbf\xc0\xb2\xc0\xfb\xc0\xce"
-"\x20\xb0\xed\xbc\xf6\xc1\xd8\x20\xb5\xa5\xc0\xcc\xc5\xcd\x20\xb1"
-"\xb8\xc1\xb6\xbf\xcd\x20\xb0\xa3\xb4\xdc\xc7\xcf\xc1\xf6\xb8\xb8"
-"\x20\xc8\xbf\xc0\xb2\xc0\xfb\xc0\xce\x20\xb0\xb4\xc3\xbc\xc1\xf6"
-"\xc7\xe2\xc7\xc1\xb7\xce\xb1\xd7\xb7\xa1\xb9\xd6\xc0\xbb\x0a\xc1"
-"\xf6\xbf\xf8\xc7\xd5\xb4\xcf\xb4\xd9\x2e\x20\xc6\xc4\xc0\xcc\xbd"
-"\xe3\xc0\xc7\x20\xbf\xec\xbe\xc6\x28\xe9\xd0\xe4\xba\x29\xc7\xd1"
-"\x20\xb9\xae\xb9\xfd\xb0\xfa\x20\xb5\xbf\xc0\xfb\x20\xc5\xb8\xc0"
-"\xcc\xc7\xce\x2c\x20\xb1\xd7\xb8\xae\xb0\xed\x20\xc0\xce\xc5\xcd"
-"\xc7\xc1\xb8\xae\xc6\xc3\x0a\xc8\xaf\xb0\xe6\xc0\xba\x20\xc6\xc4"
-"\xc0\xcc\xbd\xe3\xc0\xbb\x20\xbd\xba\xc5\xa9\xb8\xb3\xc6\xc3\xb0"
-"\xfa\x20\xbf\xa9\xb7\xaf\x20\xba\xd0\xbe\xdf\xbf\xa1\xbc\xad\xbf"
-"\xcd\x20\xb4\xeb\xba\xce\xba\xd0\xc0\xc7\x20\xc7\xc3\xb7\xa7\xc6"
-"\xfb\xbf\xa1\xbc\xad\xc0\xc7\x20\xba\xfc\xb8\xa5\x0a\xbe\xd6\xc7"
-"\xc3\xb8\xae\xc4\xc9\xc0\xcc\xbc\xc7\x20\xb0\xb3\xb9\xdf\xc0\xbb"
-"\x20\xc7\xd2\x20\xbc\xf6\x20\xc0\xd6\xb4\xc2\x20\xc0\xcc\xbb\xf3"
-"\xc0\xfb\xc0\xce\x20\xbe\xf0\xbe\xee\xb7\xce\x20\xb8\xb8\xb5\xe9"
-"\xbe\xee\xc1\xdd\xb4\xcf\xb4\xd9\x2e\x0a\x0a\xa1\xd9\xc3\xb9\xb0"
-"\xa1\xb3\xa1\x3a\x20\xb3\xaf\xbe\xc6\xb6\xf3\x20\xa4\xd4\xa4\xb6"
-"\xa4\xd0\xa4\xd4\xa4\xd4\xa4\xb6\xa4\xd0\xa4\xd4\xbe\xb1\x7e\x20"
-"\xa4\xd4\xa4\xa4\xa4\xd2\xa4\xb7\xc5\xad\x21\x20\xa4\xd4\xa4\xa8"
-"\xa4\xd1\xa4\xb7\xb1\xdd\xbe\xf8\xc0\xcc\x20\xc0\xfc\xa4\xd4\xa4"
-"\xbe\xa4\xc8\xa4\xb2\xb4\xcf\xb4\xd9\x2e\x20\xa4\xd4\xa4\xb2\xa4"
-"\xce\xa4\xaa\x2e\x20\xb1\xd7\xb7\xb1\xb0\xc5\x20\xa4\xd4\xa4\xb7"
-"\xa4\xd1\xa4\xb4\xb4\xd9\x2e\x0a",
-"\xe2\x97\x8e\x20\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\x28\x50\x79"
-"\x74\x68\x6f\x6e\x29\xec\x9d\x80\x20\xeb\xb0\xb0\xec\x9a\xb0\xea"
-"\xb8\xb0\x20\xec\x89\xbd\xea\xb3\xa0\x2c\x20\xea\xb0\x95\xeb\xa0"
-"\xa5\xed\x95\x9c\x20\xed\x94\x84\xeb\xa1\x9c\xea\xb7\xb8\xeb\x9e"
-"\x98\xeb\xb0\x8d\x20\xec\x96\xb8\xec\x96\xb4\xec\x9e\x85\xeb\x8b"
-"\x88\xeb\x8b\xa4\x2e\x20\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\xec"
-"\x9d\x80\x0a\xed\x9a\xa8\xec\x9c\xa8\xec\xa0\x81\xec\x9d\xb8\x20"
-"\xea\xb3\xa0\xec\x88\x98\xec\xa4\x80\x20\xeb\x8d\xb0\xec\x9d\xb4"
-"\xed\x84\xb0\x20\xea\xb5\xac\xec\xa1\xb0\xec\x99\x80\x20\xea\xb0"
-"\x84\xeb\x8b\xa8\xed\x95\x98\xec\xa7\x80\xeb\xa7\x8c\x20\xed\x9a"
-"\xa8\xec\x9c\xa8\xec\xa0\x81\xec\x9d\xb8\x20\xea\xb0\x9d\xec\xb2"
-"\xb4\xec\xa7\x80\xed\x96\xa5\xed\x94\x84\xeb\xa1\x9c\xea\xb7\xb8"
-"\xeb\x9e\x98\xeb\xb0\x8d\xec\x9d\x84\x0a\xec\xa7\x80\xec\x9b\x90"
-"\xed\x95\xa9\xeb\x8b\x88\xeb\x8b\xa4\x2e\x20\xed\x8c\x8c\xec\x9d"
-"\xb4\xec\x8d\xac\xec\x9d\x98\x20\xec\x9a\xb0\xec\x95\x84\x28\xe5"
-"\x84\xaa\xe9\x9b\x85\x29\xed\x95\x9c\x20\xeb\xac\xb8\xeb\xb2\x95"
-"\xea\xb3\xbc\x20\xeb\x8f\x99\xec\xa0\x81\x20\xed\x83\x80\xec\x9d"
-"\xb4\xed\x95\x91\x2c\x20\xea\xb7\xb8\xeb\xa6\xac\xea\xb3\xa0\x20"
-"\xec\x9d\xb8\xed\x84\xb0\xed\x94\x84\xeb\xa6\xac\xed\x8c\x85\x0a"
-"\xed\x99\x98\xea\xb2\xbd\xec\x9d\x80\x20\xed\x8c\x8c\xec\x9d\xb4"
-"\xec\x8d\xac\xec\x9d\x84\x20\xec\x8a\xa4\xed\x81\xac\xeb\xa6\xbd"
-"\xed\x8c\x85\xea\xb3\xbc\x20\xec\x97\xac\xeb\x9f\xac\x20\xeb\xb6"
-"\x84\xec\x95\xbc\xec\x97\x90\xec\x84\x9c\xec\x99\x80\x20\xeb\x8c"
-"\x80\xeb\xb6\x80\xeb\xb6\x84\xec\x9d\x98\x20\xed\x94\x8c\xeb\x9e"
-"\xab\xed\x8f\xbc\xec\x97\x90\xec\x84\x9c\xec\x9d\x98\x20\xeb\xb9"
-"\xa0\xeb\xa5\xb8\x0a\xec\x95\xa0\xed\x94\x8c\xeb\xa6\xac\xec\xbc"
-"\x80\xec\x9d\xb4\xec\x85\x98\x20\xea\xb0\x9c\xeb\xb0\x9c\xec\x9d"
-"\x84\x20\xed\x95\xa0\x20\xec\x88\x98\x20\xec\x9e\x88\xeb\x8a\x94"
-"\x20\xec\x9d\xb4\xec\x83\x81\xec\xa0\x81\xec\x9d\xb8\x20\xec\x96"
-"\xb8\xec\x96\xb4\xeb\xa1\x9c\x20\xeb\xa7\x8c\xeb\x93\xa4\xec\x96"
-"\xb4\xec\xa4\x8d\xeb\x8b\x88\xeb\x8b\xa4\x2e\x0a\x0a\xe2\x98\x86"
-"\xec\xb2\xab\xea\xb0\x80\xeb\x81\x9d\x3a\x20\xeb\x82\xa0\xec\x95"
-"\x84\xeb\x9d\xbc\x20\xec\x93\x94\xec\x93\x94\xec\x93\xa9\x7e\x20"
-"\xeb\x8b\x81\xed\x81\xbc\x21\x20\xeb\x9c\xbd\xea\xb8\x88\xec\x97"
-"\x86\xec\x9d\xb4\x20\xec\xa0\x84\xed\x99\xa5\xeb\x8b\x88\xeb\x8b"
-"\xa4\x2e\x20\xeb\xb7\x81\x2e\x20\xea\xb7\xb8\xeb\x9f\xb0\xea\xb1"
-"\xb0\x20\xec\x9d\x8e\xeb\x8b\xa4\x2e\x0a"),
-'gb18030': (
-"\x50\x79\x74\x68\x6f\x6e\xa3\xa8\xc5\xc9\xc9\xad\xa3\xa9\xd3\xef"
-"\xd1\xd4\xca\xc7\xd2\xbb\xd6\xd6\xb9\xa6\xc4\xdc\xc7\xbf\xb4\xf3"
-"\xb6\xf8\xcd\xea\xc9\xc6\xb5\xc4\xcd\xa8\xd3\xc3\xd0\xcd\xbc\xc6"
-"\xcb\xe3\xbb\xfa\xb3\xcc\xd0\xf2\xc9\xe8\xbc\xc6\xd3\xef\xd1\xd4"
-"\xa3\xac\x0a\xd2\xd1\xbe\xad\xbe\xdf\xd3\xd0\xca\xae\xb6\xe0\xc4"
-"\xea\xb5\xc4\xb7\xa2\xd5\xb9\xc0\xfa\xca\xb7\xa3\xac\xb3\xc9\xca"
-"\xec\xc7\xd2\xce\xc8\xb6\xa8\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1"
-"\xd4\xbe\xdf\xd3\xd0\xb7\xc7\xb3\xa3\xbc\xf2\xbd\xdd\xb6\xf8\xc7"
-"\xe5\xce\xfa\x0a\xb5\xc4\xd3\xef\xb7\xa8\xcc\xd8\xb5\xe3\xa3\xac"
-"\xca\xca\xba\xcf\xcd\xea\xb3\xc9\xb8\xf7\xd6\xd6\xb8\xdf\xb2\xe3"
-"\xc8\xce\xce\xf1\xa3\xac\xbc\xb8\xba\xf5\xbf\xc9\xd2\xd4\xd4\xda"
-"\xcb\xf9\xd3\xd0\xb5\xc4\xb2\xd9\xd7\xf7\xcf\xb5\xcd\xb3\xd6\xd0"
-"\x0a\xd4\xcb\xd0\xd0\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1\xd4\xbc"
-"\xf2\xb5\xa5\xb6\xf8\xc7\xbf\xb4\xf3\xa3\xac\xca\xca\xba\xcf\xb8"
-"\xf7\xd6\xd6\xc8\xcb\xca\xbf\xd1\xa7\xcf\xb0\xca\xb9\xd3\xc3\xa1"
-"\xa3\xc4\xbf\xc7\xb0\xa3\xac\xbb\xf9\xd3\xda\xd5\xe2\x0a\xd6\xd6"
-"\xd3\xef\xd1\xd4\xb5\xc4\xcf\xe0\xb9\xd8\xbc\xbc\xca\xf5\xd5\xfd"
-"\xd4\xda\xb7\xc9\xcb\xd9\xb5\xc4\xb7\xa2\xd5\xb9\xa3\xac\xd3\xc3"
-"\xbb\xa7\xca\xfd\xc1\xbf\xbc\xb1\xbe\xe7\xc0\xa9\xb4\xf3\xa3\xac"
-"\xcf\xe0\xb9\xd8\xb5\xc4\xd7\xca\xd4\xb4\xb7\xc7\xb3\xa3\xb6\xe0"
-"\xa1\xa3\x0a\xc8\xe7\xba\xce\xd4\xda\x20\x50\x79\x74\x68\x6f\x6e"
-"\x20\xd6\xd0\xca\xb9\xd3\xc3\xbc\xc8\xd3\xd0\xb5\xc4\x20\x43\x20"
-"\x6c\x69\x62\x72\x61\x72\x79\x3f\x0a\xa1\xa1\xd4\xda\xd9\x59\xd3"
-"\x8d\xbf\xc6\xbc\xbc\xbf\xec\xcb\xd9\xb0\x6c\xd5\xb9\xb5\xc4\xbd"
-"\xf1\xcc\xec\x2c\x20\xe9\x5f\xb0\x6c\xbc\xb0\x9c\x79\xd4\x87\xdc"
-"\x9b\xf3\x77\xb5\xc4\xcb\xd9\xb6\xc8\xca\xc7\xb2\xbb\xc8\xdd\xba"
-"\xf6\xd2\x95\xb5\xc4\x0a\xd5\x6e\xee\x7d\x2e\x20\x9e\xe9\xbc\xd3"
-"\xbf\xec\xe9\x5f\xb0\x6c\xbc\xb0\x9c\x79\xd4\x87\xb5\xc4\xcb\xd9"
-"\xb6\xc8\x2c\x20\xce\xd2\x82\x83\xb1\xe3\xb3\xa3\xcf\xa3\xcd\xfb"
-"\xc4\xdc\xc0\xfb\xd3\xc3\xd2\xbb\xd0\xa9\xd2\xd1\xe9\x5f\xb0\x6c"
-"\xba\xc3\xb5\xc4\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\x81\x4b"
-"\xd3\xd0\xd2\xbb\x82\x80\x20\x66\x61\x73\x74\x20\x70\x72\x6f\x74"
-"\x6f\x74\x79\x70\x69\x6e\x67\x20\xb5\xc4\x20\x70\x72\x6f\x67\x72"
-"\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x20"
-"\xbf\xc9\x0a\xb9\xa9\xca\xb9\xd3\xc3\x2e\x20\xc4\xbf\xc7\xb0\xd3"
-"\xd0\xd4\x53\xd4\x53\xb6\xe0\xb6\xe0\xb5\xc4\x20\x6c\x69\x62\x72"
-"\x61\x72\x79\x20\xca\xc7\xd2\xd4\x20\x43\x20\x8c\x91\xb3\xc9\x2c"
-"\x20\xb6\xf8\x20\x50\x79\x74\x68\x6f\x6e\x20\xca\xc7\xd2\xbb\x82"
-"\x80\x0a\x66\x61\x73\x74\x20\x70\x72\x6f\x74\x6f\x74\x79\x70\x69"
-"\x6e\x67\x20\xb5\xc4\x20\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e"
-"\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x2e\x20\xb9\xca\xce\xd2"
-"\x82\x83\xcf\xa3\xcd\xfb\xc4\xdc\x8c\xa2\xbc\xc8\xd3\xd0\xb5\xc4"
-"\x0a\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x20\xc4\xc3\xb5\xbd\x20"
-"\x50\x79\x74\x68\x6f\x6e\x20\xb5\xc4\xad\x68\xbe\xb3\xd6\xd0\x9c"
-"\x79\xd4\x87\xbc\xb0\xd5\xfb\xba\xcf\x2e\x20\xc6\xe4\xd6\xd0\xd7"
-"\xee\xd6\xf7\xd2\xaa\xd2\xb2\xca\xc7\xce\xd2\x82\x83\xcb\xf9\x0a"
-"\xd2\xaa\xd3\x91\xd5\x93\xb5\xc4\x86\x96\xee\x7d\xbe\xcd\xca\xc7"
-"\x3a\x0a\x83\x35\xc7\x31\x83\x33\x9a\x33\x83\x32\xb1\x31\x83\x33"
-"\x95\x31\x20\x82\x37\xd1\x36\x83\x30\x8c\x34\x83\x36\x84\x33\x20"
-"\x82\x38\x89\x35\x82\x38\xfb\x36\x83\x33\x95\x35\x20\x83\x33\xd5"
-"\x31\x82\x39\x81\x35\x20\x83\x30\xfd\x39\x83\x33\x86\x30\x20\x83"
-"\x34\xdc\x33\x83\x35\xf6\x37\x83\x35\x97\x35\x20\x83\x35\xf9\x35"
-"\x83\x30\x91\x39\x82\x38\x83\x39\x82\x39\xfc\x33\x83\x30\xf0\x34"
-"\x20\x83\x32\xeb\x39\x83\x32\xeb\x35\x82\x39\x83\x39\x2e\x0a\x0a",
-"\x50\x79\x74\x68\x6f\x6e\xef\xbc\x88\xe6\xb4\xbe\xe6\xa3\xae\xef"
-"\xbc\x89\xe8\xaf\xad\xe8\xa8\x80\xe6\x98\xaf\xe4\xb8\x80\xe7\xa7"
-"\x8d\xe5\x8a\x9f\xe8\x83\xbd\xe5\xbc\xba\xe5\xa4\xa7\xe8\x80\x8c"
-"\xe5\xae\x8c\xe5\x96\x84\xe7\x9a\x84\xe9\x80\x9a\xe7\x94\xa8\xe5"
-"\x9e\x8b\xe8\xae\xa1\xe7\xae\x97\xe6\x9c\xba\xe7\xa8\x8b\xe5\xba"
-"\x8f\xe8\xae\xbe\xe8\xae\xa1\xe8\xaf\xad\xe8\xa8\x80\xef\xbc\x8c"
-"\x0a\xe5\xb7\xb2\xe7\xbb\x8f\xe5\x85\xb7\xe6\x9c\x89\xe5\x8d\x81"
-"\xe5\xa4\x9a\xe5\xb9\xb4\xe7\x9a\x84\xe5\x8f\x91\xe5\xb1\x95\xe5"
-"\x8e\x86\xe5\x8f\xb2\xef\xbc\x8c\xe6\x88\x90\xe7\x86\x9f\xe4\xb8"
-"\x94\xe7\xa8\xb3\xe5\xae\x9a\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d"
-"\xe8\xaf\xad\xe8\xa8\x80\xe5\x85\xb7\xe6\x9c\x89\xe9\x9d\x9e\xe5"
-"\xb8\xb8\xe7\xae\x80\xe6\x8d\xb7\xe8\x80\x8c\xe6\xb8\x85\xe6\x99"
-"\xb0\x0a\xe7\x9a\x84\xe8\xaf\xad\xe6\xb3\x95\xe7\x89\xb9\xe7\x82"
-"\xb9\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\xae\x8c\xe6\x88\x90"
-"\xe5\x90\x84\xe7\xa7\x8d\xe9\xab\x98\xe5\xb1\x82\xe4\xbb\xbb\xe5"
-"\x8a\xa1\xef\xbc\x8c\xe5\x87\xa0\xe4\xb9\x8e\xe5\x8f\xaf\xe4\xbb"
-"\xa5\xe5\x9c\xa8\xe6\x89\x80\xe6\x9c\x89\xe7\x9a\x84\xe6\x93\x8d"
-"\xe4\xbd\x9c\xe7\xb3\xbb\xe7\xbb\x9f\xe4\xb8\xad\x0a\xe8\xbf\x90"
-"\xe8\xa1\x8c\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d\xe8\xaf\xad\xe8"
-"\xa8\x80\xe7\xae\x80\xe5\x8d\x95\xe8\x80\x8c\xe5\xbc\xba\xe5\xa4"
-"\xa7\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\x90\x84\xe7\xa7\x8d"
-"\xe4\xba\xba\xe5\xa3\xab\xe5\xad\xa6\xe4\xb9\xa0\xe4\xbd\xbf\xe7"
-"\x94\xa8\xe3\x80\x82\xe7\x9b\xae\xe5\x89\x8d\xef\xbc\x8c\xe5\x9f"
-"\xba\xe4\xba\x8e\xe8\xbf\x99\x0a\xe7\xa7\x8d\xe8\xaf\xad\xe8\xa8"
-"\x80\xe7\x9a\x84\xe7\x9b\xb8\xe5\x85\xb3\xe6\x8a\x80\xe6\x9c\xaf"
-"\xe6\xad\xa3\xe5\x9c\xa8\xe9\xa3\x9e\xe9\x80\x9f\xe7\x9a\x84\xe5"
-"\x8f\x91\xe5\xb1\x95\xef\xbc\x8c\xe7\x94\xa8\xe6\x88\xb7\xe6\x95"
-"\xb0\xe9\x87\x8f\xe6\x80\xa5\xe5\x89\xa7\xe6\x89\xa9\xe5\xa4\xa7"
-"\xef\xbc\x8c\xe7\x9b\xb8\xe5\x85\xb3\xe7\x9a\x84\xe8\xb5\x84\xe6"
-"\xba\x90\xe9\x9d\x9e\xe5\xb8\xb8\xe5\xa4\x9a\xe3\x80\x82\x0a\xe5"
-"\xa6\x82\xe4\xbd\x95\xe5\x9c\xa8\x20\x50\x79\x74\x68\x6f\x6e\x20"
-"\xe4\xb8\xad\xe4\xbd\xbf\xe7\x94\xa8\xe6\x97\xa2\xe6\x9c\x89\xe7"
-"\x9a\x84\x20\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x3f\x0a\xe3\x80"
-"\x80\xe5\x9c\xa8\xe8\xb3\x87\xe8\xa8\x8a\xe7\xa7\x91\xe6\x8a\x80"
-"\xe5\xbf\xab\xe9\x80\x9f\xe7\x99\xbc\xe5\xb1\x95\xe7\x9a\x84\xe4"
-"\xbb\x8a\xe5\xa4\xa9\x2c\x20\xe9\x96\x8b\xe7\x99\xbc\xe5\x8f\x8a"
-"\xe6\xb8\xac\xe8\xa9\xa6\xe8\xbb\x9f\xe9\xab\x94\xe7\x9a\x84\xe9"
-"\x80\x9f\xe5\xba\xa6\xe6\x98\xaf\xe4\xb8\x8d\xe5\xae\xb9\xe5\xbf"
-"\xbd\xe8\xa6\x96\xe7\x9a\x84\x0a\xe8\xaa\xb2\xe9\xa1\x8c\x2e\x20"
-"\xe7\x82\xba\xe5\x8a\xa0\xe5\xbf\xab\xe9\x96\x8b\xe7\x99\xbc\xe5"
-"\x8f\x8a\xe6\xb8\xac\xe8\xa9\xa6\xe7\x9a\x84\xe9\x80\x9f\xe5\xba"
-"\xa6\x2c\x20\xe6\x88\x91\xe5\x80\x91\xe4\xbe\xbf\xe5\xb8\xb8\xe5"
-"\xb8\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\x88\xa9\xe7\x94\xa8\xe4\xb8"
-"\x80\xe4\xba\x9b\xe5\xb7\xb2\xe9\x96\x8b\xe7\x99\xbc\xe5\xa5\xbd"
-"\xe7\x9a\x84\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\xe4\xb8\xa6"
-"\xe6\x9c\x89\xe4\xb8\x80\xe5\x80\x8b\x20\x66\x61\x73\x74\x20\x70"
-"\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20\x70"
-"\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75"
-"\x61\x67\x65\x20\xe5\x8f\xaf\x0a\xe4\xbe\x9b\xe4\xbd\xbf\xe7\x94"
-"\xa8\x2e\x20\xe7\x9b\xae\xe5\x89\x8d\xe6\x9c\x89\xe8\xa8\xb1\xe8"
-"\xa8\xb1\xe5\xa4\x9a\xe5\xa4\x9a\xe7\x9a\x84\x20\x6c\x69\x62\x72"
-"\x61\x72\x79\x20\xe6\x98\xaf\xe4\xbb\xa5\x20\x43\x20\xe5\xaf\xab"
-"\xe6\x88\x90\x2c\x20\xe8\x80\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20"
-"\xe6\x98\xaf\xe4\xb8\x80\xe5\x80\x8b\x0a\x66\x61\x73\x74\x20\x70"
-"\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20\x70"
-"\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75"
-"\x61\x67\x65\x2e\x20\xe6\x95\x85\xe6\x88\x91\xe5\x80\x91\xe5\xb8"
-"\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\xb0\x87\xe6\x97\xa2\xe6\x9c\x89"
-"\xe7\x9a\x84\x0a\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x20\xe6\x8b"
-"\xbf\xe5\x88\xb0\x20\x50\x79\x74\x68\x6f\x6e\x20\xe7\x9a\x84\xe7"
-"\x92\xb0\xe5\xa2\x83\xe4\xb8\xad\xe6\xb8\xac\xe8\xa9\xa6\xe5\x8f"
-"\x8a\xe6\x95\xb4\xe5\x90\x88\x2e\x20\xe5\x85\xb6\xe4\xb8\xad\xe6"
-"\x9c\x80\xe4\xb8\xbb\xe8\xa6\x81\xe4\xb9\x9f\xe6\x98\xaf\xe6\x88"
-"\x91\xe5\x80\x91\xe6\x89\x80\x0a\xe8\xa6\x81\xe8\xa8\x8e\xe8\xab"
-"\x96\xe7\x9a\x84\xe5\x95\x8f\xe9\xa1\x8c\xe5\xb0\xb1\xe6\x98\xaf"
-"\x3a\x0a\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\xec\x9d\x80\x20\xea"
-"\xb0\x95\xeb\xa0\xa5\xed\x95\x9c\x20\xea\xb8\xb0\xeb\x8a\xa5\xec"
-"\x9d\x84\x20\xec\xa7\x80\xeb\x8b\x8c\x20\xeb\xb2\x94\xec\x9a\xa9"
-"\x20\xec\xbb\xb4\xed\x93\xa8\xed\x84\xb0\x20\xed\x94\x84\xeb\xa1"
-"\x9c\xea\xb7\xb8\xeb\x9e\x98\xeb\xb0\x8d\x20\xec\x96\xb8\xec\x96"
-"\xb4\xeb\x8b\xa4\x2e\x0a\x0a"),
-'gb2312': (
-"\x50\x79\x74\x68\x6f\x6e\xa3\xa8\xc5\xc9\xc9\xad\xa3\xa9\xd3\xef"
-"\xd1\xd4\xca\xc7\xd2\xbb\xd6\xd6\xb9\xa6\xc4\xdc\xc7\xbf\xb4\xf3"
-"\xb6\xf8\xcd\xea\xc9\xc6\xb5\xc4\xcd\xa8\xd3\xc3\xd0\xcd\xbc\xc6"
-"\xcb\xe3\xbb\xfa\xb3\xcc\xd0\xf2\xc9\xe8\xbc\xc6\xd3\xef\xd1\xd4"
-"\xa3\xac\x0a\xd2\xd1\xbe\xad\xbe\xdf\xd3\xd0\xca\xae\xb6\xe0\xc4"
-"\xea\xb5\xc4\xb7\xa2\xd5\xb9\xc0\xfa\xca\xb7\xa3\xac\xb3\xc9\xca"
-"\xec\xc7\xd2\xce\xc8\xb6\xa8\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1"
-"\xd4\xbe\xdf\xd3\xd0\xb7\xc7\xb3\xa3\xbc\xf2\xbd\xdd\xb6\xf8\xc7"
-"\xe5\xce\xfa\x0a\xb5\xc4\xd3\xef\xb7\xa8\xcc\xd8\xb5\xe3\xa3\xac"
-"\xca\xca\xba\xcf\xcd\xea\xb3\xc9\xb8\xf7\xd6\xd6\xb8\xdf\xb2\xe3"
-"\xc8\xce\xce\xf1\xa3\xac\xbc\xb8\xba\xf5\xbf\xc9\xd2\xd4\xd4\xda"
-"\xcb\xf9\xd3\xd0\xb5\xc4\xb2\xd9\xd7\xf7\xcf\xb5\xcd\xb3\xd6\xd0"
-"\x0a\xd4\xcb\xd0\xd0\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1\xd4\xbc"
-"\xf2\xb5\xa5\xb6\xf8\xc7\xbf\xb4\xf3\xa3\xac\xca\xca\xba\xcf\xb8"
-"\xf7\xd6\xd6\xc8\xcb\xca\xbf\xd1\xa7\xcf\xb0\xca\xb9\xd3\xc3\xa1"
-"\xa3\xc4\xbf\xc7\xb0\xa3\xac\xbb\xf9\xd3\xda\xd5\xe2\x0a\xd6\xd6"
-"\xd3\xef\xd1\xd4\xb5\xc4\xcf\xe0\xb9\xd8\xbc\xbc\xca\xf5\xd5\xfd"
-"\xd4\xda\xb7\xc9\xcb\xd9\xb5\xc4\xb7\xa2\xd5\xb9\xa3\xac\xd3\xc3"
-"\xbb\xa7\xca\xfd\xc1\xbf\xbc\xb1\xbe\xe7\xc0\xa9\xb4\xf3\xa3\xac"
-"\xcf\xe0\xb9\xd8\xb5\xc4\xd7\xca\xd4\xb4\xb7\xc7\xb3\xa3\xb6\xe0"
-"\xa1\xa3\x0a\x0a",
-"\x50\x79\x74\x68\x6f\x6e\xef\xbc\x88\xe6\xb4\xbe\xe6\xa3\xae\xef"
-"\xbc\x89\xe8\xaf\xad\xe8\xa8\x80\xe6\x98\xaf\xe4\xb8\x80\xe7\xa7"
-"\x8d\xe5\x8a\x9f\xe8\x83\xbd\xe5\xbc\xba\xe5\xa4\xa7\xe8\x80\x8c"
-"\xe5\xae\x8c\xe5\x96\x84\xe7\x9a\x84\xe9\x80\x9a\xe7\x94\xa8\xe5"
-"\x9e\x8b\xe8\xae\xa1\xe7\xae\x97\xe6\x9c\xba\xe7\xa8\x8b\xe5\xba"
-"\x8f\xe8\xae\xbe\xe8\xae\xa1\xe8\xaf\xad\xe8\xa8\x80\xef\xbc\x8c"
-"\x0a\xe5\xb7\xb2\xe7\xbb\x8f\xe5\x85\xb7\xe6\x9c\x89\xe5\x8d\x81"
-"\xe5\xa4\x9a\xe5\xb9\xb4\xe7\x9a\x84\xe5\x8f\x91\xe5\xb1\x95\xe5"
-"\x8e\x86\xe5\x8f\xb2\xef\xbc\x8c\xe6\x88\x90\xe7\x86\x9f\xe4\xb8"
-"\x94\xe7\xa8\xb3\xe5\xae\x9a\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d"
-"\xe8\xaf\xad\xe8\xa8\x80\xe5\x85\xb7\xe6\x9c\x89\xe9\x9d\x9e\xe5"
-"\xb8\xb8\xe7\xae\x80\xe6\x8d\xb7\xe8\x80\x8c\xe6\xb8\x85\xe6\x99"
-"\xb0\x0a\xe7\x9a\x84\xe8\xaf\xad\xe6\xb3\x95\xe7\x89\xb9\xe7\x82"
-"\xb9\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\xae\x8c\xe6\x88\x90"
-"\xe5\x90\x84\xe7\xa7\x8d\xe9\xab\x98\xe5\xb1\x82\xe4\xbb\xbb\xe5"
-"\x8a\xa1\xef\xbc\x8c\xe5\x87\xa0\xe4\xb9\x8e\xe5\x8f\xaf\xe4\xbb"
-"\xa5\xe5\x9c\xa8\xe6\x89\x80\xe6\x9c\x89\xe7\x9a\x84\xe6\x93\x8d"
-"\xe4\xbd\x9c\xe7\xb3\xbb\xe7\xbb\x9f\xe4\xb8\xad\x0a\xe8\xbf\x90"
-"\xe8\xa1\x8c\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d\xe8\xaf\xad\xe8"
-"\xa8\x80\xe7\xae\x80\xe5\x8d\x95\xe8\x80\x8c\xe5\xbc\xba\xe5\xa4"
-"\xa7\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\x90\x84\xe7\xa7\x8d"
-"\xe4\xba\xba\xe5\xa3\xab\xe5\xad\xa6\xe4\xb9\xa0\xe4\xbd\xbf\xe7"
-"\x94\xa8\xe3\x80\x82\xe7\x9b\xae\xe5\x89\x8d\xef\xbc\x8c\xe5\x9f"
-"\xba\xe4\xba\x8e\xe8\xbf\x99\x0a\xe7\xa7\x8d\xe8\xaf\xad\xe8\xa8"
-"\x80\xe7\x9a\x84\xe7\x9b\xb8\xe5\x85\xb3\xe6\x8a\x80\xe6\x9c\xaf"
-"\xe6\xad\xa3\xe5\x9c\xa8\xe9\xa3\x9e\xe9\x80\x9f\xe7\x9a\x84\xe5"
-"\x8f\x91\xe5\xb1\x95\xef\xbc\x8c\xe7\x94\xa8\xe6\x88\xb7\xe6\x95"
-"\xb0\xe9\x87\x8f\xe6\x80\xa5\xe5\x89\xa7\xe6\x89\xa9\xe5\xa4\xa7"
-"\xef\xbc\x8c\xe7\x9b\xb8\xe5\x85\xb3\xe7\x9a\x84\xe8\xb5\x84\xe6"
-"\xba\x90\xe9\x9d\x9e\xe5\xb8\xb8\xe5\xa4\x9a\xe3\x80\x82\x0a\x0a"),
-'gbk': (
-"\x50\x79\x74\x68\x6f\x6e\xa3\xa8\xc5\xc9\xc9\xad\xa3\xa9\xd3\xef"
-"\xd1\xd4\xca\xc7\xd2\xbb\xd6\xd6\xb9\xa6\xc4\xdc\xc7\xbf\xb4\xf3"
-"\xb6\xf8\xcd\xea\xc9\xc6\xb5\xc4\xcd\xa8\xd3\xc3\xd0\xcd\xbc\xc6"
-"\xcb\xe3\xbb\xfa\xb3\xcc\xd0\xf2\xc9\xe8\xbc\xc6\xd3\xef\xd1\xd4"
-"\xa3\xac\x0a\xd2\xd1\xbe\xad\xbe\xdf\xd3\xd0\xca\xae\xb6\xe0\xc4"
-"\xea\xb5\xc4\xb7\xa2\xd5\xb9\xc0\xfa\xca\xb7\xa3\xac\xb3\xc9\xca"
-"\xec\xc7\xd2\xce\xc8\xb6\xa8\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1"
-"\xd4\xbe\xdf\xd3\xd0\xb7\xc7\xb3\xa3\xbc\xf2\xbd\xdd\xb6\xf8\xc7"
-"\xe5\xce\xfa\x0a\xb5\xc4\xd3\xef\xb7\xa8\xcc\xd8\xb5\xe3\xa3\xac"
-"\xca\xca\xba\xcf\xcd\xea\xb3\xc9\xb8\xf7\xd6\xd6\xb8\xdf\xb2\xe3"
-"\xc8\xce\xce\xf1\xa3\xac\xbc\xb8\xba\xf5\xbf\xc9\xd2\xd4\xd4\xda"
-"\xcb\xf9\xd3\xd0\xb5\xc4\xb2\xd9\xd7\xf7\xcf\xb5\xcd\xb3\xd6\xd0"
-"\x0a\xd4\xcb\xd0\xd0\xa1\xa3\xd5\xe2\xd6\xd6\xd3\xef\xd1\xd4\xbc"
-"\xf2\xb5\xa5\xb6\xf8\xc7\xbf\xb4\xf3\xa3\xac\xca\xca\xba\xcf\xb8"
-"\xf7\xd6\xd6\xc8\xcb\xca\xbf\xd1\xa7\xcf\xb0\xca\xb9\xd3\xc3\xa1"
-"\xa3\xc4\xbf\xc7\xb0\xa3\xac\xbb\xf9\xd3\xda\xd5\xe2\x0a\xd6\xd6"
-"\xd3\xef\xd1\xd4\xb5\xc4\xcf\xe0\xb9\xd8\xbc\xbc\xca\xf5\xd5\xfd"
-"\xd4\xda\xb7\xc9\xcb\xd9\xb5\xc4\xb7\xa2\xd5\xb9\xa3\xac\xd3\xc3"
-"\xbb\xa7\xca\xfd\xc1\xbf\xbc\xb1\xbe\xe7\xc0\xa9\xb4\xf3\xa3\xac"
-"\xcf\xe0\xb9\xd8\xb5\xc4\xd7\xca\xd4\xb4\xb7\xc7\xb3\xa3\xb6\xe0"
-"\xa1\xa3\x0a\xc8\xe7\xba\xce\xd4\xda\x20\x50\x79\x74\x68\x6f\x6e"
-"\x20\xd6\xd0\xca\xb9\xd3\xc3\xbc\xc8\xd3\xd0\xb5\xc4\x20\x43\x20"
-"\x6c\x69\x62\x72\x61\x72\x79\x3f\x0a\xa1\xa1\xd4\xda\xd9\x59\xd3"
-"\x8d\xbf\xc6\xbc\xbc\xbf\xec\xcb\xd9\xb0\x6c\xd5\xb9\xb5\xc4\xbd"
-"\xf1\xcc\xec\x2c\x20\xe9\x5f\xb0\x6c\xbc\xb0\x9c\x79\xd4\x87\xdc"
-"\x9b\xf3\x77\xb5\xc4\xcb\xd9\xb6\xc8\xca\xc7\xb2\xbb\xc8\xdd\xba"
-"\xf6\xd2\x95\xb5\xc4\x0a\xd5\x6e\xee\x7d\x2e\x20\x9e\xe9\xbc\xd3"
-"\xbf\xec\xe9\x5f\xb0\x6c\xbc\xb0\x9c\x79\xd4\x87\xb5\xc4\xcb\xd9"
-"\xb6\xc8\x2c\x20\xce\xd2\x82\x83\xb1\xe3\xb3\xa3\xcf\xa3\xcd\xfb"
-"\xc4\xdc\xc0\xfb\xd3\xc3\xd2\xbb\xd0\xa9\xd2\xd1\xe9\x5f\xb0\x6c"
-"\xba\xc3\xb5\xc4\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\x81\x4b"
-"\xd3\xd0\xd2\xbb\x82\x80\x20\x66\x61\x73\x74\x20\x70\x72\x6f\x74"
-"\x6f\x74\x79\x70\x69\x6e\x67\x20\xb5\xc4\x20\x70\x72\x6f\x67\x72"
-"\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x20"
-"\xbf\xc9\x0a\xb9\xa9\xca\xb9\xd3\xc3\x2e\x20\xc4\xbf\xc7\xb0\xd3"
-"\xd0\xd4\x53\xd4\x53\xb6\xe0\xb6\xe0\xb5\xc4\x20\x6c\x69\x62\x72"
-"\x61\x72\x79\x20\xca\xc7\xd2\xd4\x20\x43\x20\x8c\x91\xb3\xc9\x2c"
-"\x20\xb6\xf8\x20\x50\x79\x74\x68\x6f\x6e\x20\xca\xc7\xd2\xbb\x82"
-"\x80\x0a\x66\x61\x73\x74\x20\x70\x72\x6f\x74\x6f\x74\x79\x70\x69"
-"\x6e\x67\x20\xb5\xc4\x20\x70\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e"
-"\x67\x20\x6c\x61\x6e\x67\x75\x61\x67\x65\x2e\x20\xb9\xca\xce\xd2"
-"\x82\x83\xcf\xa3\xcd\xfb\xc4\xdc\x8c\xa2\xbc\xc8\xd3\xd0\xb5\xc4"
-"\x0a\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x20\xc4\xc3\xb5\xbd\x20"
-"\x50\x79\x74\x68\x6f\x6e\x20\xb5\xc4\xad\x68\xbe\xb3\xd6\xd0\x9c"
-"\x79\xd4\x87\xbc\xb0\xd5\xfb\xba\xcf\x2e\x20\xc6\xe4\xd6\xd0\xd7"
-"\xee\xd6\xf7\xd2\xaa\xd2\xb2\xca\xc7\xce\xd2\x82\x83\xcb\xf9\x0a"
-"\xd2\xaa\xd3\x91\xd5\x93\xb5\xc4\x86\x96\xee\x7d\xbe\xcd\xca\xc7"
-"\x3a\x0a\x0a",
-"\x50\x79\x74\x68\x6f\x6e\xef\xbc\x88\xe6\xb4\xbe\xe6\xa3\xae\xef"
-"\xbc\x89\xe8\xaf\xad\xe8\xa8\x80\xe6\x98\xaf\xe4\xb8\x80\xe7\xa7"
-"\x8d\xe5\x8a\x9f\xe8\x83\xbd\xe5\xbc\xba\xe5\xa4\xa7\xe8\x80\x8c"
-"\xe5\xae\x8c\xe5\x96\x84\xe7\x9a\x84\xe9\x80\x9a\xe7\x94\xa8\xe5"
-"\x9e\x8b\xe8\xae\xa1\xe7\xae\x97\xe6\x9c\xba\xe7\xa8\x8b\xe5\xba"
-"\x8f\xe8\xae\xbe\xe8\xae\xa1\xe8\xaf\xad\xe8\xa8\x80\xef\xbc\x8c"
-"\x0a\xe5\xb7\xb2\xe7\xbb\x8f\xe5\x85\xb7\xe6\x9c\x89\xe5\x8d\x81"
-"\xe5\xa4\x9a\xe5\xb9\xb4\xe7\x9a\x84\xe5\x8f\x91\xe5\xb1\x95\xe5"
-"\x8e\x86\xe5\x8f\xb2\xef\xbc\x8c\xe6\x88\x90\xe7\x86\x9f\xe4\xb8"
-"\x94\xe7\xa8\xb3\xe5\xae\x9a\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d"
-"\xe8\xaf\xad\xe8\xa8\x80\xe5\x85\xb7\xe6\x9c\x89\xe9\x9d\x9e\xe5"
-"\xb8\xb8\xe7\xae\x80\xe6\x8d\xb7\xe8\x80\x8c\xe6\xb8\x85\xe6\x99"
-"\xb0\x0a\xe7\x9a\x84\xe8\xaf\xad\xe6\xb3\x95\xe7\x89\xb9\xe7\x82"
-"\xb9\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\xae\x8c\xe6\x88\x90"
-"\xe5\x90\x84\xe7\xa7\x8d\xe9\xab\x98\xe5\xb1\x82\xe4\xbb\xbb\xe5"
-"\x8a\xa1\xef\xbc\x8c\xe5\x87\xa0\xe4\xb9\x8e\xe5\x8f\xaf\xe4\xbb"
-"\xa5\xe5\x9c\xa8\xe6\x89\x80\xe6\x9c\x89\xe7\x9a\x84\xe6\x93\x8d"
-"\xe4\xbd\x9c\xe7\xb3\xbb\xe7\xbb\x9f\xe4\xb8\xad\x0a\xe8\xbf\x90"
-"\xe8\xa1\x8c\xe3\x80\x82\xe8\xbf\x99\xe7\xa7\x8d\xe8\xaf\xad\xe8"
-"\xa8\x80\xe7\xae\x80\xe5\x8d\x95\xe8\x80\x8c\xe5\xbc\xba\xe5\xa4"
-"\xa7\xef\xbc\x8c\xe9\x80\x82\xe5\x90\x88\xe5\x90\x84\xe7\xa7\x8d"
-"\xe4\xba\xba\xe5\xa3\xab\xe5\xad\xa6\xe4\xb9\xa0\xe4\xbd\xbf\xe7"
-"\x94\xa8\xe3\x80\x82\xe7\x9b\xae\xe5\x89\x8d\xef\xbc\x8c\xe5\x9f"
-"\xba\xe4\xba\x8e\xe8\xbf\x99\x0a\xe7\xa7\x8d\xe8\xaf\xad\xe8\xa8"
-"\x80\xe7\x9a\x84\xe7\x9b\xb8\xe5\x85\xb3\xe6\x8a\x80\xe6\x9c\xaf"
-"\xe6\xad\xa3\xe5\x9c\xa8\xe9\xa3\x9e\xe9\x80\x9f\xe7\x9a\x84\xe5"
-"\x8f\x91\xe5\xb1\x95\xef\xbc\x8c\xe7\x94\xa8\xe6\x88\xb7\xe6\x95"
-"\xb0\xe9\x87\x8f\xe6\x80\xa5\xe5\x89\xa7\xe6\x89\xa9\xe5\xa4\xa7"
-"\xef\xbc\x8c\xe7\x9b\xb8\xe5\x85\xb3\xe7\x9a\x84\xe8\xb5\x84\xe6"
-"\xba\x90\xe9\x9d\x9e\xe5\xb8\xb8\xe5\xa4\x9a\xe3\x80\x82\x0a\xe5"
-"\xa6\x82\xe4\xbd\x95\xe5\x9c\xa8\x20\x50\x79\x74\x68\x6f\x6e\x20"
-"\xe4\xb8\xad\xe4\xbd\xbf\xe7\x94\xa8\xe6\x97\xa2\xe6\x9c\x89\xe7"
-"\x9a\x84\x20\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x3f\x0a\xe3\x80"
-"\x80\xe5\x9c\xa8\xe8\xb3\x87\xe8\xa8\x8a\xe7\xa7\x91\xe6\x8a\x80"
-"\xe5\xbf\xab\xe9\x80\x9f\xe7\x99\xbc\xe5\xb1\x95\xe7\x9a\x84\xe4"
-"\xbb\x8a\xe5\xa4\xa9\x2c\x20\xe9\x96\x8b\xe7\x99\xbc\xe5\x8f\x8a"
-"\xe6\xb8\xac\xe8\xa9\xa6\xe8\xbb\x9f\xe9\xab\x94\xe7\x9a\x84\xe9"
-"\x80\x9f\xe5\xba\xa6\xe6\x98\xaf\xe4\xb8\x8d\xe5\xae\xb9\xe5\xbf"
-"\xbd\xe8\xa6\x96\xe7\x9a\x84\x0a\xe8\xaa\xb2\xe9\xa1\x8c\x2e\x20"
-"\xe7\x82\xba\xe5\x8a\xa0\xe5\xbf\xab\xe9\x96\x8b\xe7\x99\xbc\xe5"
-"\x8f\x8a\xe6\xb8\xac\xe8\xa9\xa6\xe7\x9a\x84\xe9\x80\x9f\xe5\xba"
-"\xa6\x2c\x20\xe6\x88\x91\xe5\x80\x91\xe4\xbe\xbf\xe5\xb8\xb8\xe5"
-"\xb8\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\x88\xa9\xe7\x94\xa8\xe4\xb8"
-"\x80\xe4\xba\x9b\xe5\xb7\xb2\xe9\x96\x8b\xe7\x99\xbc\xe5\xa5\xbd"
-"\xe7\x9a\x84\x0a\x6c\x69\x62\x72\x61\x72\x79\x2c\x20\xe4\xb8\xa6"
-"\xe6\x9c\x89\xe4\xb8\x80\xe5\x80\x8b\x20\x66\x61\x73\x74\x20\x70"
-"\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20\x70"
-"\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75"
-"\x61\x67\x65\x20\xe5\x8f\xaf\x0a\xe4\xbe\x9b\xe4\xbd\xbf\xe7\x94"
-"\xa8\x2e\x20\xe7\x9b\xae\xe5\x89\x8d\xe6\x9c\x89\xe8\xa8\xb1\xe8"
-"\xa8\xb1\xe5\xa4\x9a\xe5\xa4\x9a\xe7\x9a\x84\x20\x6c\x69\x62\x72"
-"\x61\x72\x79\x20\xe6\x98\xaf\xe4\xbb\xa5\x20\x43\x20\xe5\xaf\xab"
-"\xe6\x88\x90\x2c\x20\xe8\x80\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20"
-"\xe6\x98\xaf\xe4\xb8\x80\xe5\x80\x8b\x0a\x66\x61\x73\x74\x20\x70"
-"\x72\x6f\x74\x6f\x74\x79\x70\x69\x6e\x67\x20\xe7\x9a\x84\x20\x70"
-"\x72\x6f\x67\x72\x61\x6d\x6d\x69\x6e\x67\x20\x6c\x61\x6e\x67\x75"
-"\x61\x67\x65\x2e\x20\xe6\x95\x85\xe6\x88\x91\xe5\x80\x91\xe5\xb8"
-"\x8c\xe6\x9c\x9b\xe8\x83\xbd\xe5\xb0\x87\xe6\x97\xa2\xe6\x9c\x89"
-"\xe7\x9a\x84\x0a\x43\x20\x6c\x69\x62\x72\x61\x72\x79\x20\xe6\x8b"
-"\xbf\xe5\x88\xb0\x20\x50\x79\x74\x68\x6f\x6e\x20\xe7\x9a\x84\xe7"
-"\x92\xb0\xe5\xa2\x83\xe4\xb8\xad\xe6\xb8\xac\xe8\xa9\xa6\xe5\x8f"
-"\x8a\xe6\x95\xb4\xe5\x90\x88\x2e\x20\xe5\x85\xb6\xe4\xb8\xad\xe6"
-"\x9c\x80\xe4\xb8\xbb\xe8\xa6\x81\xe4\xb9\x9f\xe6\x98\xaf\xe6\x88"
-"\x91\xe5\x80\x91\xe6\x89\x80\x0a\xe8\xa6\x81\xe8\xa8\x8e\xe8\xab"
-"\x96\xe7\x9a\x84\xe5\x95\x8f\xe9\xa1\x8c\xe5\xb0\xb1\xe6\x98\xaf"
-"\x3a\x0a\x0a"),
-'johab': (
-"\x99\xb1\xa4\x77\x88\x62\xd0\x61\x20\xcd\x5c\xaf\xa1\xc5\xa9\x9c"
-"\x61\x0a\x0a\xdc\xc0\xdc\xc0\x90\x73\x21\x21\x20\xf1\x67\xe2\x9c"
-"\xf0\x55\xcc\x81\xa3\x89\x9f\x85\x8a\xa1\x20\xdc\xde\xdc\xd3\xd2"
-"\x7a\xd9\xaf\xd9\xaf\xd9\xaf\x20\x8b\x77\x96\xd3\x20\xdc\xd1\x95"
-"\x81\x20\xdc\xc0\x2e\x20\x2e\x0a\xed\x3c\xb5\x77\xdc\xd1\x93\x77"
-"\xd2\x73\x20\x2e\x20\x2e\x20\x2e\x20\x2e\x20\xac\xe1\xb6\x89\x9e"
-"\xa1\x20\x95\x65\xd0\x62\xf0\xe0\x20\xe0\x3b\xd2\x7a\x20\x21\x20"
-"\x21\x20\x21\x87\x41\x2e\x87\x41\x0a\xd3\x61\xd3\x61\xd3\x61\x20"
-"\x88\x41\x88\x41\x88\x41\xd9\x69\x87\x41\x5f\x87\x41\x20\xb4\xe1"
-"\x9f\x9a\x20\xc8\xa1\xc5\xc1\x8b\x7a\x20\x95\x61\xb7\x77\x20\xc3"
-"\x97\xe2\x9c\x97\x69\xf0\xe0\x20\xdc\xc0\x97\x61\x8b\x7a\x0a\xac"
-"\xe9\x9f\x7a\x20\xe0\x3b\xd2\x7a\x20\x2e\x20\x2e\x20\x2e\x20\x2e"
-"\x20\x8a\x89\xb4\x81\xae\xba\x20\xdc\xd1\x8a\xa1\x20\xdc\xde\x9f"
-"\x89\xdc\xc2\x8b\x7a\x20\xf1\x67\xf1\x62\xf5\x49\xed\xfc\xf3\xe9"
-"\x8c\x61\xbb\x9a\x0a\xb5\xc1\xb2\xa1\xd2\x7a\x20\x21\x20\x21\x20"
-"\xed\x3c\xb5\x77\xdc\xd1\x20\xe0\x3b\x93\x77\x8a\xa1\x20\xd9\x69"
-"\xea\xbe\x89\xc5\x20\xb4\xf4\x93\x77\x8a\xa1\x93\x77\x20\xed\x3c"
-"\x93\x77\x96\xc1\xd2\x7a\x20\x8b\x69\xb4\x81\x97\x7a\x0a\xdc\xde"
-"\x9d\x61\x97\x41\xe2\x9c\x20\xaf\x81\xce\xa1\xae\xa1\xd2\x7a\x20"
-"\xb4\xe1\x9f\x9a\x20\xf1\x67\xf1\x62\xf5\x49\xed\xfc\xf3\xe9\xaf"
-"\x82\xdc\xef\x97\x69\xb4\x7a\x21\x21\x20\xdc\xc0\xdc\xc0\x90\x73"
-"\xd9\xbd\x20\xd9\x62\xd9\x62\x2a\x0a\x0a",
-"\xeb\x98\xa0\xeb\xb0\xa9\xea\xb0\x81\xed\x95\x98\x20\xed\x8e\xb2"
-"\xec\x8b\x9c\xec\xbd\x9c\xeb\x9d\xbc\x0a\x0a\xe3\x89\xaf\xe3\x89"
-"\xaf\xeb\x82\xa9\x21\x21\x20\xe5\x9b\xa0\xe4\xb9\x9d\xe6\x9c\x88"
-"\xed\x8c\xa8\xeb\xaf\xa4\xeb\xa6\x94\xea\xb6\x88\x20\xe2\x93\xa1"
-"\xe2\x93\x96\xed\x9b\x80\xc2\xbf\xc2\xbf\xc2\xbf\x20\xea\xb8\x8d"
-"\xeb\x92\x99\x20\xe2\x93\x94\xeb\x8e\xa8\x20\xe3\x89\xaf\x2e\x20"
-"\x2e\x0a\xe4\xba\x9e\xec\x98\x81\xe2\x93\x94\xeb\x8a\xa5\xed\x9a"
-"\xb9\x20\x2e\x20\x2e\x20\x2e\x20\x2e\x20\xec\x84\x9c\xec\x9a\xb8"
-"\xeb\xa4\x84\x20\xeb\x8e\x90\xed\x95\x99\xe4\xb9\x99\x20\xe5\xae"
-"\xb6\xed\x9b\x80\x20\x21\x20\x21\x20\x21\xe3\x85\xa0\x2e\xe3\x85"
-"\xa0\x0a\xed\x9d\x90\xed\x9d\x90\xed\x9d\x90\x20\xe3\x84\xb1\xe3"
-"\x84\xb1\xe3\x84\xb1\xe2\x98\x86\xe3\x85\xa0\x5f\xe3\x85\xa0\x20"
-"\xec\x96\xb4\xeb\xa6\xa8\x20\xed\x83\xb8\xec\xbd\xb0\xea\xb8\x90"
-"\x20\xeb\x8e\x8c\xec\x9d\x91\x20\xec\xb9\x91\xe4\xb9\x9d\xeb\x93"
-"\xa4\xe4\xb9\x99\x20\xe3\x89\xaf\xeb\x93\x9c\xea\xb8\x90\x0a\xec"
-"\x84\xa4\xeb\xa6\x8c\x20\xe5\xae\xb6\xed\x9b\x80\x20\x2e\x20\x2e"
-"\x20\x2e\x20\x2e\x20\xea\xb5\xb4\xec\x95\xa0\xec\x89\x8c\x20\xe2"
-"\x93\x94\xea\xb6\x88\x20\xe2\x93\xa1\xeb\xa6\x98\xe3\x89\xb1\xea"
-"\xb8\x90\x20\xe5\x9b\xa0\xe4\xbb\x81\xe5\xb7\x9d\xef\xa6\x81\xe4"
-"\xb8\xad\xea\xb9\x8c\xec\xa6\xbc\x0a\xec\x99\x80\xec\x92\x80\xed"
-"\x9b\x80\x20\x21\x20\x21\x20\xe4\xba\x9e\xec\x98\x81\xe2\x93\x94"
-"\x20\xe5\xae\xb6\xeb\x8a\xa5\xea\xb6\x88\x20\xe2\x98\x86\xe4\xb8"
-"\x8a\xea\xb4\x80\x20\xec\x97\x86\xeb\x8a\xa5\xea\xb6\x88\xeb\x8a"
-"\xa5\x20\xe4\xba\x9e\xeb\x8a\xa5\xeb\x92\x88\xed\x9b\x80\x20\xea"
-"\xb8\x80\xec\x95\xa0\xeb\x93\xb4\x0a\xe2\x93\xa1\xeb\xa0\xa4\xeb"
-"\x93\x80\xe4\xb9\x9d\x20\xec\x8b\x80\xed\x92\x94\xec\x88\xb4\xed"
-"\x9b\x80\x20\xec\x96\xb4\xeb\xa6\xa8\x20\xe5\x9b\xa0\xe4\xbb\x81"
-"\xe5\xb7\x9d\xef\xa6\x81\xe4\xb8\xad\xec\x8b\x81\xe2\x91\xa8\xeb"
-"\x93\xa4\xec\x95\x9c\x21\x21\x20\xe3\x89\xaf\xe3\x89\xaf\xeb\x82"
-"\xa9\xe2\x99\xa1\x20\xe2\x8c\x92\xe2\x8c\x92\x2a\x0a\x0a"),
-'shift_jis': (
-"\x50\x79\x74\x68\x6f\x6e\x20\x82\xcc\x8a\x4a\x94\xad\x82\xcd\x81"
-"\x41\x31\x39\x39\x30\x20\x94\x4e\x82\xb2\x82\xeb\x82\xa9\x82\xe7"
-"\x8a\x4a\x8e\x6e\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb7"
-"\x81\x42\x0a\x8a\x4a\x94\xad\x8e\xd2\x82\xcc\x20\x47\x75\x69\x64"
-"\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73\x73\x75\x6d\x20\x82\xcd\x8b"
-"\xb3\x88\xe7\x97\x70\x82\xcc\x83\x76\x83\x8d\x83\x4f\x83\x89\x83"
-"\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea\x81\x75\x41\x42\x43\x81\x76"
-"\x82\xcc\x8a\x4a\x94\xad\x82\xc9\x8e\x51\x89\xc1\x82\xb5\x82\xc4"
-"\x82\xa2\x82\xdc\x82\xb5\x82\xbd\x82\xaa\x81\x41\x41\x42\x43\x20"
-"\x82\xcd\x8e\xc0\x97\x70\x8f\xe3\x82\xcc\x96\xda\x93\x49\x82\xc9"
-"\x82\xcd\x82\xa0\x82\xdc\x82\xe8\x93\x4b\x82\xb5\x82\xc4\x82\xa2"
-"\x82\xdc\x82\xb9\x82\xf1\x82\xc5\x82\xb5\x82\xbd\x81\x42\x0a\x82"
-"\xb1\x82\xcc\x82\xbd\x82\xdf\x81\x41\x47\x75\x69\x64\x6f\x20\x82"
-"\xcd\x82\xe6\x82\xe8\x8e\xc0\x97\x70\x93\x49\x82\xc8\x83\x76\x83"
-"\x8d\x83\x4f\x83\x89\x83\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea\x82"
-"\xcc\x8a\x4a\x94\xad\x82\xf0\x8a\x4a\x8e\x6e\x82\xb5\x81\x41\x89"
-"\x70\x8d\x91\x20\x42\x42\x53\x20\x95\xfa\x91\x97\x82\xcc\x83\x52"
-"\x83\x81\x83\x66\x83\x42\x94\xd4\x91\x67\x81\x75\x83\x82\x83\x93"
-"\x83\x65\x83\x42\x20\x83\x70\x83\x43\x83\x5c\x83\x93\x81\x76\x82"
-"\xcc\x83\x74\x83\x40\x83\x93\x82\xc5\x82\xa0\x82\xe9\x20\x47\x75"
-"\x69\x64\x6f\x20\x82\xcd\x82\xb1\x82\xcc\x8c\xbe\x8c\xea\x82\xf0"
-"\x81\x75\x50\x79\x74\x68\x6f\x6e\x81\x76\x82\xc6\x96\xbc\x82\xc3"
-"\x82\xaf\x82\xdc\x82\xb5\x82\xbd\x81\x42\x0a\x82\xb1\x82\xcc\x82"
-"\xe6\x82\xa4\x82\xc8\x94\x77\x8c\x69\x82\xa9\x82\xe7\x90\xb6\x82"
-"\xdc\x82\xea\x82\xbd\x20\x50\x79\x74\x68\x6f\x6e\x20\x82\xcc\x8c"
-"\xbe\x8c\xea\x90\xdd\x8c\x76\x82\xcd\x81\x41\x81\x75\x83\x56\x83"
-"\x93\x83\x76\x83\x8b\x81\x76\x82\xc5\x81\x75\x8f\x4b\x93\xbe\x82"
-"\xaa\x97\x65\x88\xd5\x81\x76\x82\xc6\x82\xa2\x82\xa4\x96\xda\x95"
-"\x57\x82\xc9\x8f\x64\x93\x5f\x82\xaa\x92\x75\x82\xa9\x82\xea\x82"
-"\xc4\x82\xa2\x82\xdc\x82\xb7\x81\x42\x0a\x91\xbd\x82\xad\x82\xcc"
-"\x83\x58\x83\x4e\x83\x8a\x83\x76\x83\x67\x8c\x6e\x8c\xbe\x8c\xea"
-"\x82\xc5\x82\xcd\x83\x86\x81\x5b\x83\x55\x82\xcc\x96\xda\x90\xe6"
-"\x82\xcc\x97\x98\x95\xd6\x90\xab\x82\xf0\x97\x44\x90\xe6\x82\xb5"
-"\x82\xc4\x90\x46\x81\x58\x82\xc8\x8b\x40\x94\x5c\x82\xf0\x8c\xbe"
-"\x8c\xea\x97\x76\x91\x66\x82\xc6\x82\xb5\x82\xc4\x8e\xe6\x82\xe8"
-"\x93\xfc\x82\xea\x82\xe9\x8f\xea\x8d\x87\x82\xaa\x91\xbd\x82\xa2"
-"\x82\xcc\x82\xc5\x82\xb7\x82\xaa\x81\x41\x50\x79\x74\x68\x6f\x6e"
-"\x20\x82\xc5\x82\xcd\x82\xbb\x82\xa4\x82\xa2\x82\xc1\x82\xbd\x8f"
-"\xac\x8d\xd7\x8d\x48\x82\xaa\x92\xc7\x89\xc1\x82\xb3\x82\xea\x82"
-"\xe9\x82\xb1\x82\xc6\x82\xcd\x82\xa0\x82\xdc\x82\xe8\x82\xa0\x82"
-"\xe8\x82\xdc\x82\xb9\x82\xf1\x81\x42\x0a\x8c\xbe\x8c\xea\x8e\xa9"
-"\x91\xcc\x82\xcc\x8b\x40\x94\x5c\x82\xcd\x8d\xc5\x8f\xac\x8c\xc0"
-"\x82\xc9\x89\x9f\x82\xb3\x82\xa6\x81\x41\x95\x4b\x97\x76\x82\xc8"
-"\x8b\x40\x94\x5c\x82\xcd\x8a\x67\x92\xa3\x83\x82\x83\x57\x83\x85"
-"\x81\x5b\x83\x8b\x82\xc6\x82\xb5\x82\xc4\x92\xc7\x89\xc1\x82\xb7"
-"\x82\xe9\x81\x41\x82\xc6\x82\xa2\x82\xa4\x82\xcc\x82\xaa\x20\x50"
-"\x79\x74\x68\x6f\x6e\x20\x82\xcc\x83\x7c\x83\x8a\x83\x56\x81\x5b"
-"\x82\xc5\x82\xb7\x81\x42\x0a\x0a",
-"\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xaf\xe3\x80\x81\x31\x39\x39\x30\x20\xe5\xb9\xb4\xe3\x81"
-"\x94\xe3\x82\x8d\xe3\x81\x8b\xe3\x82\x89\xe9\x96\x8b\xe5\xa7\x8b"
-"\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3"
-"\x81\x99\xe3\x80\x82\x0a\xe9\x96\x8b\xe7\x99\xba\xe8\x80\x85\xe3"
-"\x81\xae\x20\x47\x75\x69\x64\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73"
-"\x73\x75\x6d\x20\xe3\x81\xaf\xe6\x95\x99\xe8\x82\xb2\xe7\x94\xa8"
-"\xe3\x81\xae\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3"
-"\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e\xe3\x80"
-"\x8c\x41\x42\x43\xe3\x80\x8d\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xab\xe5\x8f\x82\xe5\x8a\xa0\xe3\x81\x97\xe3\x81\xa6\xe3"
-"\x81\x84\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x81\x8c\xe3\x80"
-"\x81\x41\x42\x43\x20\xe3\x81\xaf\xe5\xae\x9f\xe7\x94\xa8\xe4\xb8"
-"\x8a\xe3\x81\xae\xe7\x9b\xae\xe7\x9a\x84\xe3\x81\xab\xe3\x81\xaf"
-"\xe3\x81\x82\xe3\x81\xbe\xe3\x82\x8a\xe9\x81\xa9\xe3\x81\x97\xe3"
-"\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x81"
-"\xa7\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a\xe3\x81\x93\xe3\x81"
-"\xae\xe3\x81\x9f\xe3\x82\x81\xe3\x80\x81\x47\x75\x69\x64\x6f\x20"
-"\xe3\x81\xaf\xe3\x82\x88\xe3\x82\x8a\xe5\xae\x9f\xe7\x94\xa8\xe7"
-"\x9a\x84\xe3\x81\xaa\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83"
-"\xa9\xe3\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e"
-"\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba\xe3\x82\x92\xe9\x96\x8b\xe5"
-"\xa7\x8b\xe3\x81\x97\xe3\x80\x81\xe8\x8b\xb1\xe5\x9b\xbd\x20\x42"
-"\x42\x53\x20\xe6\x94\xbe\xe9\x80\x81\xe3\x81\xae\xe3\x82\xb3\xe3"
-"\x83\xa1\xe3\x83\x87\xe3\x82\xa3\xe7\x95\xaa\xe7\xb5\x84\xe3\x80"
-"\x8c\xe3\x83\xa2\xe3\x83\xb3\xe3\x83\x86\xe3\x82\xa3\x20\xe3\x83"
-"\x91\xe3\x82\xa4\xe3\x82\xbd\xe3\x83\xb3\xe3\x80\x8d\xe3\x81\xae"
-"\xe3\x83\x95\xe3\x82\xa1\xe3\x83\xb3\xe3\x81\xa7\xe3\x81\x82\xe3"
-"\x82\x8b\x20\x47\x75\x69\x64\x6f\x20\xe3\x81\xaf\xe3\x81\x93\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe3\x82\x92\xe3\x80\x8c\x50\x79"
-"\x74\x68\x6f\x6e\xe3\x80\x8d\xe3\x81\xa8\xe5\x90\x8d\xe3\x81\xa5"
-"\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a"
-"\xe3\x81\x93\xe3\x81\xae\xe3\x82\x88\xe3\x81\x86\xe3\x81\xaa\xe8"
-"\x83\x8c\xe6\x99\xaf\xe3\x81\x8b\xe3\x82\x89\xe7\x94\x9f\xe3\x81"
-"\xbe\xe3\x82\x8c\xe3\x81\x9f\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa8\xad\xe8\xa8\x88\xe3\x81"
-"\xaf\xe3\x80\x81\xe3\x80\x8c\xe3\x82\xb7\xe3\x83\xb3\xe3\x83\x97"
-"\xe3\x83\xab\xe3\x80\x8d\xe3\x81\xa7\xe3\x80\x8c\xe7\xbf\x92\xe5"
-"\xbe\x97\xe3\x81\x8c\xe5\xae\xb9\xe6\x98\x93\xe3\x80\x8d\xe3\x81"
-"\xa8\xe3\x81\x84\xe3\x81\x86\xe7\x9b\xae\xe6\xa8\x99\xe3\x81\xab"
-"\xe9\x87\x8d\xe7\x82\xb9\xe3\x81\x8c\xe7\xbd\xae\xe3\x81\x8b\xe3"
-"\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80"
-"\x82\x0a\xe5\xa4\x9a\xe3\x81\x8f\xe3\x81\xae\xe3\x82\xb9\xe3\x82"
-"\xaf\xe3\x83\xaa\xe3\x83\x97\xe3\x83\x88\xe7\xb3\xbb\xe8\xa8\x80"
-"\xe8\xaa\x9e\xe3\x81\xa7\xe3\x81\xaf\xe3\x83\xa6\xe3\x83\xbc\xe3"
-"\x82\xb6\xe3\x81\xae\xe7\x9b\xae\xe5\x85\x88\xe3\x81\xae\xe5\x88"
-"\xa9\xe4\xbe\xbf\xe6\x80\xa7\xe3\x82\x92\xe5\x84\xaa\xe5\x85\x88"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\x89\xb2\xe3\x80\x85\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x82\x92\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa6"
-"\x81\xe7\xb4\xa0\xe3\x81\xa8\xe3\x81\x97\xe3\x81\xa6\xe5\x8f\x96"
-"\xe3\x82\x8a\xe5\x85\xa5\xe3\x82\x8c\xe3\x82\x8b\xe5\xa0\xb4\xe5"
-"\x90\x88\xe3\x81\x8c\xe5\xa4\x9a\xe3\x81\x84\xe3\x81\xae\xe3\x81"
-"\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe3\x81\xa7\xe3\x81\xaf\xe3\x81\x9d\xe3\x81\x86\xe3\x81\x84"
-"\xe3\x81\xa3\xe3\x81\x9f\xe5\xb0\x8f\xe7\xb4\xb0\xe5\xb7\xa5\xe3"
-"\x81\x8c\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x95\xe3\x82\x8c\xe3\x82"
-"\x8b\xe3\x81\x93\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\x82\xe3\x81\xbe"
-"\xe3\x82\x8a\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3"
-"\x82\x93\xe3\x80\x82\x0a\xe8\xa8\x80\xe8\xaa\x9e\xe8\x87\xaa\xe4"
-"\xbd\x93\xe3\x81\xae\xe6\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x9c"
-"\x80\xe5\xb0\x8f\xe9\x99\x90\xe3\x81\xab\xe6\x8a\xbc\xe3\x81\x95"
-"\xe3\x81\x88\xe3\x80\x81\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x8b\xa1\xe5\xbc\xb5\xe3\x83"
-"\xa2\xe3\x82\xb8\xe3\x83\xa5\xe3\x83\xbc\xe3\x83\xab\xe3\x81\xa8"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x99\xe3"
-"\x82\x8b\xe3\x80\x81\xe3\x81\xa8\xe3\x81\x84\xe3\x81\x86\xe3\x81"
-"\xae\xe3\x81\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe3"
-"\x83\x9d\xe3\x83\xaa\xe3\x82\xb7\xe3\x83\xbc\xe3\x81\xa7\xe3\x81"
-"\x99\xe3\x80\x82\x0a\x0a"),
-'shift_jisx0213': (
-"\x50\x79\x74\x68\x6f\x6e\x20\x82\xcc\x8a\x4a\x94\xad\x82\xcd\x81"
-"\x41\x31\x39\x39\x30\x20\x94\x4e\x82\xb2\x82\xeb\x82\xa9\x82\xe7"
-"\x8a\x4a\x8e\x6e\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb7"
-"\x81\x42\x0a\x8a\x4a\x94\xad\x8e\xd2\x82\xcc\x20\x47\x75\x69\x64"
-"\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73\x73\x75\x6d\x20\x82\xcd\x8b"
-"\xb3\x88\xe7\x97\x70\x82\xcc\x83\x76\x83\x8d\x83\x4f\x83\x89\x83"
-"\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea\x81\x75\x41\x42\x43\x81\x76"
-"\x82\xcc\x8a\x4a\x94\xad\x82\xc9\x8e\x51\x89\xc1\x82\xb5\x82\xc4"
-"\x82\xa2\x82\xdc\x82\xb5\x82\xbd\x82\xaa\x81\x41\x41\x42\x43\x20"
-"\x82\xcd\x8e\xc0\x97\x70\x8f\xe3\x82\xcc\x96\xda\x93\x49\x82\xc9"
-"\x82\xcd\x82\xa0\x82\xdc\x82\xe8\x93\x4b\x82\xb5\x82\xc4\x82\xa2"
-"\x82\xdc\x82\xb9\x82\xf1\x82\xc5\x82\xb5\x82\xbd\x81\x42\x0a\x82"
-"\xb1\x82\xcc\x82\xbd\x82\xdf\x81\x41\x47\x75\x69\x64\x6f\x20\x82"
-"\xcd\x82\xe6\x82\xe8\x8e\xc0\x97\x70\x93\x49\x82\xc8\x83\x76\x83"
-"\x8d\x83\x4f\x83\x89\x83\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea\x82"
-"\xcc\x8a\x4a\x94\xad\x82\xf0\x8a\x4a\x8e\x6e\x82\xb5\x81\x41\x89"
-"\x70\x8d\x91\x20\x42\x42\x53\x20\x95\xfa\x91\x97\x82\xcc\x83\x52"
-"\x83\x81\x83\x66\x83\x42\x94\xd4\x91\x67\x81\x75\x83\x82\x83\x93"
-"\x83\x65\x83\x42\x20\x83\x70\x83\x43\x83\x5c\x83\x93\x81\x76\x82"
-"\xcc\x83\x74\x83\x40\x83\x93\x82\xc5\x82\xa0\x82\xe9\x20\x47\x75"
-"\x69\x64\x6f\x20\x82\xcd\x82\xb1\x82\xcc\x8c\xbe\x8c\xea\x82\xf0"
-"\x81\x75\x50\x79\x74\x68\x6f\x6e\x81\x76\x82\xc6\x96\xbc\x82\xc3"
-"\x82\xaf\x82\xdc\x82\xb5\x82\xbd\x81\x42\x0a\x82\xb1\x82\xcc\x82"
-"\xe6\x82\xa4\x82\xc8\x94\x77\x8c\x69\x82\xa9\x82\xe7\x90\xb6\x82"
-"\xdc\x82\xea\x82\xbd\x20\x50\x79\x74\x68\x6f\x6e\x20\x82\xcc\x8c"
-"\xbe\x8c\xea\x90\xdd\x8c\x76\x82\xcd\x81\x41\x81\x75\x83\x56\x83"
-"\x93\x83\x76\x83\x8b\x81\x76\x82\xc5\x81\x75\x8f\x4b\x93\xbe\x82"
-"\xaa\x97\x65\x88\xd5\x81\x76\x82\xc6\x82\xa2\x82\xa4\x96\xda\x95"
-"\x57\x82\xc9\x8f\x64\x93\x5f\x82\xaa\x92\x75\x82\xa9\x82\xea\x82"
-"\xc4\x82\xa2\x82\xdc\x82\xb7\x81\x42\x0a\x91\xbd\x82\xad\x82\xcc"
-"\x83\x58\x83\x4e\x83\x8a\x83\x76\x83\x67\x8c\x6e\x8c\xbe\x8c\xea"
-"\x82\xc5\x82\xcd\x83\x86\x81\x5b\x83\x55\x82\xcc\x96\xda\x90\xe6"
-"\x82\xcc\x97\x98\x95\xd6\x90\xab\x82\xf0\x97\x44\x90\xe6\x82\xb5"
-"\x82\xc4\x90\x46\x81\x58\x82\xc8\x8b\x40\x94\x5c\x82\xf0\x8c\xbe"
-"\x8c\xea\x97\x76\x91\x66\x82\xc6\x82\xb5\x82\xc4\x8e\xe6\x82\xe8"
-"\x93\xfc\x82\xea\x82\xe9\x8f\xea\x8d\x87\x82\xaa\x91\xbd\x82\xa2"
-"\x82\xcc\x82\xc5\x82\xb7\x82\xaa\x81\x41\x50\x79\x74\x68\x6f\x6e"
-"\x20\x82\xc5\x82\xcd\x82\xbb\x82\xa4\x82\xa2\x82\xc1\x82\xbd\x8f"
-"\xac\x8d\xd7\x8d\x48\x82\xaa\x92\xc7\x89\xc1\x82\xb3\x82\xea\x82"
-"\xe9\x82\xb1\x82\xc6\x82\xcd\x82\xa0\x82\xdc\x82\xe8\x82\xa0\x82"
-"\xe8\x82\xdc\x82\xb9\x82\xf1\x81\x42\x0a\x8c\xbe\x8c\xea\x8e\xa9"
-"\x91\xcc\x82\xcc\x8b\x40\x94\x5c\x82\xcd\x8d\xc5\x8f\xac\x8c\xc0"
-"\x82\xc9\x89\x9f\x82\xb3\x82\xa6\x81\x41\x95\x4b\x97\x76\x82\xc8"
-"\x8b\x40\x94\x5c\x82\xcd\x8a\x67\x92\xa3\x83\x82\x83\x57\x83\x85"
-"\x81\x5b\x83\x8b\x82\xc6\x82\xb5\x82\xc4\x92\xc7\x89\xc1\x82\xb7"
-"\x82\xe9\x81\x41\x82\xc6\x82\xa2\x82\xa4\x82\xcc\x82\xaa\x20\x50"
-"\x79\x74\x68\x6f\x6e\x20\x82\xcc\x83\x7c\x83\x8a\x83\x56\x81\x5b"
-"\x82\xc5\x82\xb7\x81\x42\x0a\x0a\x83\x6d\x82\xf5\x20\x83\x9e\x20"
-"\x83\x67\x83\x4c\x88\x4b\x88\x79\x20\x98\x83\xfc\xd6\x20\xfc\xd2"
-"\xfc\xe6\xfb\xd4\x0a",
-"\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xaf\xe3\x80\x81\x31\x39\x39\x30\x20\xe5\xb9\xb4\xe3\x81"
-"\x94\xe3\x82\x8d\xe3\x81\x8b\xe3\x82\x89\xe9\x96\x8b\xe5\xa7\x8b"
-"\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3"
-"\x81\x99\xe3\x80\x82\x0a\xe9\x96\x8b\xe7\x99\xba\xe8\x80\x85\xe3"
-"\x81\xae\x20\x47\x75\x69\x64\x6f\x20\x76\x61\x6e\x20\x52\x6f\x73"
-"\x73\x75\x6d\x20\xe3\x81\xaf\xe6\x95\x99\xe8\x82\xb2\xe7\x94\xa8"
-"\xe3\x81\xae\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3"
-"\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e\xe3\x80"
-"\x8c\x41\x42\x43\xe3\x80\x8d\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba"
-"\xe3\x81\xab\xe5\x8f\x82\xe5\x8a\xa0\xe3\x81\x97\xe3\x81\xa6\xe3"
-"\x81\x84\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x81\x8c\xe3\x80"
-"\x81\x41\x42\x43\x20\xe3\x81\xaf\xe5\xae\x9f\xe7\x94\xa8\xe4\xb8"
-"\x8a\xe3\x81\xae\xe7\x9b\xae\xe7\x9a\x84\xe3\x81\xab\xe3\x81\xaf"
-"\xe3\x81\x82\xe3\x81\xbe\xe3\x82\x8a\xe9\x81\xa9\xe3\x81\x97\xe3"
-"\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x81"
-"\xa7\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a\xe3\x81\x93\xe3\x81"
-"\xae\xe3\x81\x9f\xe3\x82\x81\xe3\x80\x81\x47\x75\x69\x64\x6f\x20"
-"\xe3\x81\xaf\xe3\x82\x88\xe3\x82\x8a\xe5\xae\x9f\xe7\x94\xa8\xe7"
-"\x9a\x84\xe3\x81\xaa\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83"
-"\xa9\xe3\x83\x9f\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e"
-"\xe3\x81\xae\xe9\x96\x8b\xe7\x99\xba\xe3\x82\x92\xe9\x96\x8b\xe5"
-"\xa7\x8b\xe3\x81\x97\xe3\x80\x81\xe8\x8b\xb1\xe5\x9b\xbd\x20\x42"
-"\x42\x53\x20\xe6\x94\xbe\xe9\x80\x81\xe3\x81\xae\xe3\x82\xb3\xe3"
-"\x83\xa1\xe3\x83\x87\xe3\x82\xa3\xe7\x95\xaa\xe7\xb5\x84\xe3\x80"
-"\x8c\xe3\x83\xa2\xe3\x83\xb3\xe3\x83\x86\xe3\x82\xa3\x20\xe3\x83"
-"\x91\xe3\x82\xa4\xe3\x82\xbd\xe3\x83\xb3\xe3\x80\x8d\xe3\x81\xae"
-"\xe3\x83\x95\xe3\x82\xa1\xe3\x83\xb3\xe3\x81\xa7\xe3\x81\x82\xe3"
-"\x82\x8b\x20\x47\x75\x69\x64\x6f\x20\xe3\x81\xaf\xe3\x81\x93\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe3\x82\x92\xe3\x80\x8c\x50\x79"
-"\x74\x68\x6f\x6e\xe3\x80\x8d\xe3\x81\xa8\xe5\x90\x8d\xe3\x81\xa5"
-"\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x97\xe3\x81\x9f\xe3\x80\x82\x0a"
-"\xe3\x81\x93\xe3\x81\xae\xe3\x82\x88\xe3\x81\x86\xe3\x81\xaa\xe8"
-"\x83\x8c\xe6\x99\xaf\xe3\x81\x8b\xe3\x82\x89\xe7\x94\x9f\xe3\x81"
-"\xbe\xe3\x82\x8c\xe3\x81\x9f\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3"
-"\x81\xae\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa8\xad\xe8\xa8\x88\xe3\x81"
-"\xaf\xe3\x80\x81\xe3\x80\x8c\xe3\x82\xb7\xe3\x83\xb3\xe3\x83\x97"
-"\xe3\x83\xab\xe3\x80\x8d\xe3\x81\xa7\xe3\x80\x8c\xe7\xbf\x92\xe5"
-"\xbe\x97\xe3\x81\x8c\xe5\xae\xb9\xe6\x98\x93\xe3\x80\x8d\xe3\x81"
-"\xa8\xe3\x81\x84\xe3\x81\x86\xe7\x9b\xae\xe6\xa8\x99\xe3\x81\xab"
-"\xe9\x87\x8d\xe7\x82\xb9\xe3\x81\x8c\xe7\xbd\xae\xe3\x81\x8b\xe3"
-"\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80"
-"\x82\x0a\xe5\xa4\x9a\xe3\x81\x8f\xe3\x81\xae\xe3\x82\xb9\xe3\x82"
-"\xaf\xe3\x83\xaa\xe3\x83\x97\xe3\x83\x88\xe7\xb3\xbb\xe8\xa8\x80"
-"\xe8\xaa\x9e\xe3\x81\xa7\xe3\x81\xaf\xe3\x83\xa6\xe3\x83\xbc\xe3"
-"\x82\xb6\xe3\x81\xae\xe7\x9b\xae\xe5\x85\x88\xe3\x81\xae\xe5\x88"
-"\xa9\xe4\xbe\xbf\xe6\x80\xa7\xe3\x82\x92\xe5\x84\xaa\xe5\x85\x88"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\x89\xb2\xe3\x80\x85\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x82\x92\xe8\xa8\x80\xe8\xaa\x9e\xe8\xa6"
-"\x81\xe7\xb4\xa0\xe3\x81\xa8\xe3\x81\x97\xe3\x81\xa6\xe5\x8f\x96"
-"\xe3\x82\x8a\xe5\x85\xa5\xe3\x82\x8c\xe3\x82\x8b\xe5\xa0\xb4\xe5"
-"\x90\x88\xe3\x81\x8c\xe5\xa4\x9a\xe3\x81\x84\xe3\x81\xae\xe3\x81"
-"\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\x50\x79\x74\x68\x6f\x6e"
-"\x20\xe3\x81\xa7\xe3\x81\xaf\xe3\x81\x9d\xe3\x81\x86\xe3\x81\x84"
-"\xe3\x81\xa3\xe3\x81\x9f\xe5\xb0\x8f\xe7\xb4\xb0\xe5\xb7\xa5\xe3"
-"\x81\x8c\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x95\xe3\x82\x8c\xe3\x82"
-"\x8b\xe3\x81\x93\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\x82\xe3\x81\xbe"
-"\xe3\x82\x8a\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3"
-"\x82\x93\xe3\x80\x82\x0a\xe8\xa8\x80\xe8\xaa\x9e\xe8\x87\xaa\xe4"
-"\xbd\x93\xe3\x81\xae\xe6\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x9c"
-"\x80\xe5\xb0\x8f\xe9\x99\x90\xe3\x81\xab\xe6\x8a\xbc\xe3\x81\x95"
-"\xe3\x81\x88\xe3\x80\x81\xe5\xbf\x85\xe8\xa6\x81\xe3\x81\xaa\xe6"
-"\xa9\x9f\xe8\x83\xbd\xe3\x81\xaf\xe6\x8b\xa1\xe5\xbc\xb5\xe3\x83"
-"\xa2\xe3\x82\xb8\xe3\x83\xa5\xe3\x83\xbc\xe3\x83\xab\xe3\x81\xa8"
-"\xe3\x81\x97\xe3\x81\xa6\xe8\xbf\xbd\xe5\x8a\xa0\xe3\x81\x99\xe3"
-"\x82\x8b\xe3\x80\x81\xe3\x81\xa8\xe3\x81\x84\xe3\x81\x86\xe3\x81"
-"\xae\xe3\x81\x8c\x20\x50\x79\x74\x68\x6f\x6e\x20\xe3\x81\xae\xe3"
-"\x83\x9d\xe3\x83\xaa\xe3\x82\xb7\xe3\x83\xbc\xe3\x81\xa7\xe3\x81"
-"\x99\xe3\x80\x82\x0a\x0a\xe3\x83\x8e\xe3\x81\x8b\xe3\x82\x9a\x20"
-"\xe3\x83\x88\xe3\x82\x9a\x20\xe3\x83\x88\xe3\x82\xad\xef\xa8\xb6"
-"\xef\xa8\xb9\x20\xf0\xa1\x9a\xb4\xf0\xaa\x8e\x8c\x20\xe9\xba\x80"
-"\xe9\xbd\x81\xf0\xa9\x9b\xb0\x0a"),
-}
diff --git a/Lib/test/decimaltestdata/extra.decTest b/Lib/test/decimaltestdata/extra.decTest
index fe8b77a..b630d8e 100644
--- a/Lib/test/decimaltestdata/extra.decTest
+++ b/Lib/test/decimaltestdata/extra.decTest
@@ -222,12 +222,25 @@
extr1701 power 100.0 -557.71e-742888888 -> 1.000000000000000 Inexact Rounded
extr1702 power 10 1e-100 -> 1.000000000000000 Inexact Rounded
+-- Another one (see issue #12080). Thanks again to Stefan Krah.
+extr1703 power 4 -1.2e-999999999 -> 1.000000000000000 Inexact Rounded
+
-- A couple of interesting exact cases for power. Note that the specification
-- requires these to be reported as Inexact.
extr1710 power 1e375 56e-3 -> 1.000000000000000E+21 Inexact Rounded
extr1711 power 10000 0.75 -> 1000.000000000000 Inexact Rounded
extr1712 power 1e-24 0.875 -> 1.000000000000000E-21 Inexact Rounded
+-- Some more exact cases, exercising power with negative second argument.
+extr1720 power 400 -0.5 -> 0.05000000000000000 Inexact Rounded
+extr1721 power 4096 -0.75 -> 0.001953125000000000 Inexact Rounded
+extr1722 power 625e4 -0.25 -> 0.02000000000000000 Inexact Rounded
+
+-- Nonexact cases, to exercise some of the early exit conditions from
+-- _power_exact.
+extr1730 power 2048 -0.75 -> 0.003284751622084822 Inexact Rounded
+
+
-- Tests for the is_* boolean operations
precision: 9
maxExponent: 999
diff --git a/Lib/test/nokia.pem b/Lib/test/nokia.pem
new file mode 100644
index 0000000..0d044df
--- /dev/null
+++ b/Lib/test/nokia.pem
@@ -0,0 +1,31 @@
+# Certificate for projects.developer.nokia.com:443 (see issue 13034)
+-----BEGIN CERTIFICATE-----
+MIIFLDCCBBSgAwIBAgIQLubqdkCgdc7lAF9NfHlUmjANBgkqhkiG9w0BAQUFADCB
+vDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
+ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug
+YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDE2MDQGA1UEAxMt
+VmVyaVNpZ24gQ2xhc3MgMyBJbnRlcm5hdGlvbmFsIFNlcnZlciBDQSAtIEczMB4X
+DTExMDkyMTAwMDAwMFoXDTEyMDkyMDIzNTk1OVowcTELMAkGA1UEBhMCRkkxDjAM
+BgNVBAgTBUVzcG9vMQ4wDAYDVQQHFAVFc3BvbzEOMAwGA1UEChQFTm9raWExCzAJ
+BgNVBAsUAkJJMSUwIwYDVQQDFBxwcm9qZWN0cy5kZXZlbG9wZXIubm9raWEuY29t
+MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCr92w1bpHYSYxUEx8N/8Iddda2
+lYi+aXNtQfV/l2Fw9Ykv3Ipw4nLeGTj18FFlAZgMdPRlgrzF/NNXGw/9l3/qKdow
+CypkQf8lLaxb9Ze1E/KKmkRJa48QTOqvo6GqKuTI6HCeGlG1RxDb8YSKcQWLiytn
+yj3Wp4MgRQO266xmMQIDAQABo4IB9jCCAfIwQQYDVR0RBDowOIIccHJvamVjdHMu
+ZGV2ZWxvcGVyLm5va2lhLmNvbYIYcHJvamVjdHMuZm9ydW0ubm9raWEuY29tMAkG
+A1UdEwQCMAAwCwYDVR0PBAQDAgWgMEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHA6Ly9T
+VlJJbnRsLUczLWNybC52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNybDBEBgNVHSAE
+PTA7MDkGC2CGSAGG+EUBBxcDMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZl
+cmlzaWduLmNvbS9ycGEwKAYDVR0lBCEwHwYJYIZIAYb4QgQBBggrBgEFBQcDAQYI
+KwYBBQUHAwIwcgYIKwYBBQUHAQEEZjBkMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz
+cC52ZXJpc2lnbi5jb20wPAYIKwYBBQUHMAKGMGh0dHA6Ly9TVlJJbnRsLUczLWFp
+YS52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNlcjBuBggrBgEFBQcBDARiMGChXqBc
+MFowWDBWFglpbWFnZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsH
+iyEFGDAmFiRodHRwOi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJ
+KoZIhvcNAQEFBQADggEBACQuPyIJqXwUyFRWw9x5yDXgMW4zYFopQYOw/ItRY522
+O5BsySTh56BWS6mQB07XVfxmYUGAvRQDA5QHpmY8jIlNwSmN3s8RKo+fAtiNRlcL
+x/mWSfuMs3D/S6ev3D6+dpEMZtjrhOdctsarMKp8n/hPbwhAbg5hVjpkW5n8vz2y
+0KxvvkA1AxpLwpVv7OlK17ttzIHw8bp9HTlHBU5s8bKz4a565V/a5HI0CSEv/+0y
+ko4/ghTnZc1CkmUngKKeFMSah/mT/xAh8XnE2l1AazFa8UKuYki1e+ArHaGZc4ix
+UYOtiRphwfuYQhRZ7qX9q2MMkCMI65XNK/SaFrAbbG0=
+-----END CERTIFICATE-----
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index c9e74b8..2e3875c 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -124,6 +124,19 @@
class use_metaclass(object):
__metaclass__ = metaclass
+class pickling_metaclass(type):
+ def __eq__(self, other):
+ return (type(self) == type(other) and
+ self.reduce_args == other.reduce_args)
+
+ def __reduce__(self):
+ return (create_dynamic_class, self.reduce_args)
+
+def create_dynamic_class(name, bases):
+ result = pickling_metaclass(name, bases, dict())
+ result.reduce_args = (name, bases)
+ return result
+
# DATA0 .. DATA2 are the pickles we expect under the various protocols, for
# the object returned by create_data().
@@ -609,6 +622,14 @@
b = self.loads(s)
self.assertEqual(a.__class__, b.__class__)
+ def test_dynamic_class(self):
+ a = create_dynamic_class("my_dynamic_class", (object,))
+ copy_reg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
+ for proto in protocols:
+ s = self.dumps(a, proto)
+ b = self.loads(s)
+ self.assertEqual(a, b)
+
def test_structseq(self):
import time
import os
diff --git a/Lib/test/test_StringIO.py b/Lib/test/test_StringIO.py
index 4774c6d..76fc3d7 100644
--- a/Lib/test/test_StringIO.py
+++ b/Lib/test/test_StringIO.py
@@ -100,6 +100,10 @@
self._fp.close()
self.assertRaises(ValueError, self._fp.next)
+ def test_getvalue(self):
+ self._fp.close()
+ self.assertRaises(ValueError, self._fp.getvalue)
+
class TestStringIO(TestGenericStringIO):
MODULE = StringIO
diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index b6c0f1b..acf5b8f 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -4,6 +4,7 @@
"""
import unittest
+import warnings
from test import test_support
from weakref import proxy
import array, cStringIO
@@ -783,7 +784,9 @@
def test_subclass_with_kwargs(self):
# SF bug #1486663 -- this used to erroneously raise a TypeError
- ArraySubclassWithKwargs('b', newarg=1)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", '', DeprecationWarning)
+ ArraySubclassWithKwargs('b', newarg=1)
class StringTest(BaseTest):
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index c1574ec..e3aa5b1 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -20,10 +20,24 @@
# These tests are compiled through "exec"
# There should be atleast one test per statement
exec_tests = [
+ # None
+ "None",
# FunctionDef
"def f(): pass",
+ # FunctionDef with arg
+ "def f(a): pass",
+ # FunctionDef with arg and default value
+ "def f(a=0): pass",
+ # FunctionDef with varargs
+ "def f(*args): pass",
+ # FunctionDef with kwargs
+ "def f(**kwargs): pass",
+ # FunctionDef with all kind of args
+ "def f(a, b=1, c=None, d=[], e={}, *args, **kwargs): pass",
# ClassDef
"class C:pass",
+ # ClassDef, new style class
+ "class C(object): pass",
# Return
"def f():return 1",
# Delete
@@ -68,6 +82,27 @@
"for a,b in c: pass",
"[(a,b) for a,b in c]",
"((a,b) for a,b in c)",
+ "((a,b) for (a,b) in c)",
+ # Multiline generator expression (test for .lineno & .col_offset)
+ """(
+ (
+ Aa
+ ,
+ Bb
+ )
+ for
+ Aa
+ ,
+ Bb in Cc
+ )""",
+ # dictcomp
+ "{a : b for w in x for m in p if g}",
+ # dictcomp with naked tuple
+ "{a : b for v,w in x}",
+ # setcomp
+ "{r for l in x if g}",
+ # setcomp with naked tuple
+ "{r for l,m in x}",
]
# These are compiled through "single"
@@ -80,6 +115,8 @@
# These are compiled through "eval"
# It should test all expressions
eval_tests = [
+ # None
+ "None",
# BoolOp
"a and b",
# BinOp
@@ -90,6 +127,16 @@
"lambda:None",
# Dict
"{ 1:2 }",
+ # Empty dict
+ "{}",
+ # Set
+ "{None,}",
+ # Multiline dict (test for .lineno & .col_offset)
+ """{
+ 1
+ :
+ 2
+ }""",
# ListComp
"[a for b in c if d]",
# GeneratorExp
@@ -114,8 +161,14 @@
"v",
# List
"[1,2,3]",
+ # Empty list
+ "[]",
# Tuple
"1,2,3",
+ # Tuple
+ "(1,2,3)",
+ # Empty tuple
+ "()",
# Combination
"a.b.c.d(a.b[1:2])",
@@ -141,6 +194,23 @@
elif value is not None:
self._assertTrueorder(value, parent_pos)
+ def test_AST_objects(self):
+ x = ast.AST()
+ self.assertEqual(x._fields, ())
+
+ with self.assertRaises(AttributeError):
+ x.vararg
+
+ with self.assertRaises(AttributeError):
+ x.foobar = 21
+
+ with self.assertRaises(AttributeError):
+ ast.AST(lineno=2)
+
+ with self.assertRaises(TypeError):
+ # "_ast.AST constructor takes 0 positional arguments"
+ ast.AST(2)
+
def test_snippets(self):
for input, output, kind in ((exec_tests, exec_results, "exec"),
(single_tests, single_results, "single"),
@@ -169,7 +239,83 @@
self.assertTrue(issubclass(ast.comprehension, ast.AST))
self.assertTrue(issubclass(ast.Gt, ast.AST))
+ def test_field_attr_existence(self):
+ for name, item in ast.__dict__.iteritems():
+ if isinstance(item, type) and name != 'AST' and name[0].isupper():
+ x = item()
+ if isinstance(x, ast.AST):
+ self.assertEqual(type(x._fields), tuple)
+
+ def test_arguments(self):
+ x = ast.arguments()
+ self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults'))
+
+ with self.assertRaises(AttributeError):
+ x.vararg
+
+ x = ast.arguments(1, 2, 3, 4)
+ self.assertEqual(x.vararg, 2)
+
+ def test_field_attr_writable(self):
+ x = ast.Num()
+ # We can assign to _fields
+ x._fields = 666
+ self.assertEqual(x._fields, 666)
+
+ def test_classattrs(self):
+ x = ast.Num()
+ self.assertEqual(x._fields, ('n',))
+
+ with self.assertRaises(AttributeError):
+ x.n
+
+ x = ast.Num(42)
+ self.assertEqual(x.n, 42)
+
+ with self.assertRaises(AttributeError):
+ x.lineno
+
+ with self.assertRaises(AttributeError):
+ x.foobar
+
+ x = ast.Num(lineno=2)
+ self.assertEqual(x.lineno, 2)
+
+ x = ast.Num(42, lineno=0)
+ self.assertEqual(x.lineno, 0)
+ self.assertEqual(x._fields, ('n',))
+ self.assertEqual(x.n, 42)
+
+ self.assertRaises(TypeError, ast.Num, 1, 2)
+ self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
+
+ def test_module(self):
+ body = [ast.Num(42)]
+ x = ast.Module(body)
+ self.assertEqual(x.body, body)
+
def test_nodeclasses(self):
+ # Zero arguments constructor explicitely allowed
+ x = ast.BinOp()
+ self.assertEqual(x._fields, ('left', 'op', 'right'))
+
+ # Random attribute allowed too
+ x.foobarbaz = 5
+ self.assertEqual(x.foobarbaz, 5)
+
+ n1 = ast.Num(1)
+ n3 = ast.Num(3)
+ addop = ast.Add()
+ x = ast.BinOp(n1, addop, n3)
+ self.assertEqual(x.left, n1)
+ self.assertEqual(x.op, addop)
+ self.assertEqual(x.right, n3)
+
+ x = ast.BinOp(1, 2, 3)
+ self.assertEqual(x.left, 1)
+ self.assertEqual(x.op, 2)
+ self.assertEqual(x.right, 3)
+
x = ast.BinOp(1, 2, 3, lineno=0)
self.assertEqual(x.left, 1)
self.assertEqual(x.op, 2)
@@ -178,6 +324,12 @@
# node raises exception when not given enough arguments
self.assertRaises(TypeError, ast.BinOp, 1, 2)
+ # node raises exception when given too many arguments
+ self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
+ # node raises exception when not given enough arguments
+ self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
+ # node raises exception when given too many arguments
+ self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
# can set attributes through kwargs too
x = ast.BinOp(left=1, op=2, right=3, lineno=0)
@@ -186,8 +338,14 @@
self.assertEqual(x.right, 3)
self.assertEqual(x.lineno, 0)
+ # Random kwargs also allowed
+ x = ast.BinOp(1, 2, 3, foobarbaz=42)
+ self.assertEqual(x.foobarbaz, 42)
+
+ def test_no_fields(self):
# this used to fail because Sub._fields was None
x = ast.Sub()
+ self.assertEqual(x._fields, ())
def test_pickling(self):
import pickle
@@ -204,6 +362,20 @@
ast2 = mod.loads(mod.dumps(ast, protocol))
self.assertEqual(to_tuple(ast2), to_tuple(ast))
+ def test_invalid_identitifer(self):
+ m = ast.Module([ast.Expr(ast.Name(u"x", ast.Load()))])
+ ast.fix_missing_locations(m)
+ with self.assertRaises(TypeError) as cm:
+ compile(m, "<test>", "exec")
+ self.assertIn("identifier must be of type str", str(cm.exception))
+
+ def test_invalid_string(self):
+ m = ast.Module([ast.Expr(ast.Str(43))])
+ ast.fix_missing_locations(m)
+ with self.assertRaises(TypeError) as cm:
+ compile(m, "<test>", "exec")
+ self.assertIn("string must be of type str or uni", str(cm.exception))
+
class ASTHelpers_Test(unittest.TestCase):
@@ -330,8 +502,15 @@
#### EVERYTHING BELOW IS GENERATED #####
exec_results = [
+('Module', [('Expr', (1, 0), ('Name', (1, 0), 'None', ('Load',)))]),
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Pass', (1, 9))], [])]),
+('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',))], None, None, []), [('Pass', (1, 10))], [])]),
+('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',))], None, None, [('Num', (1, 8), 0)]), [('Pass', (1, 12))], [])]),
+('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], 'args', None, []), [('Pass', (1, 14))], [])]),
+('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, 'kwargs', []), [('Pass', (1, 17))], [])]),
+('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',)), ('Name', (1, 9), 'b', ('Param',)), ('Name', (1, 14), 'c', ('Param',)), ('Name', (1, 22), 'd', ('Param',)), ('Name', (1, 28), 'e', ('Param',))], 'args', 'kwargs', [('Num', (1, 11), 1), ('Name', (1, 16), 'None', ('Load',)), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Pass', (1, 52))], [])]),
('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))], [])]),
+('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [('Pass', (1, 17))], [])]),
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [])]),
('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
@@ -355,16 +534,26 @@
('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [])]),
('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]),
('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]),
+('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 12), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [])]))]),
+('Module', [('Expr', (1, 0), ('GeneratorExp', (2, 4), ('Tuple', (3, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [])]))]),
+('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), []), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))])]))]),
+('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'v', ('Store',)), ('Name', (1, 13), 'w', ('Store',))], ('Store',)), ('Name', (1, 18), 'x', ('Load',)), [])]))]),
+('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))])]))]),
+('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7), [('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 9), 'm', ('Store',))], ('Store',)), ('Name', (1, 14), 'x', ('Load',)), [])]))]),
]
single_results = [
('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
]
eval_results = [
+('Expression', ('Name', (1, 0), 'None', ('Load',))),
('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, []), ('Name', (1, 7), 'None', ('Load',)))),
('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
+('Expression', ('Dict', (1, 0), [], [])),
+('Expression', ('Set', (1, 0), [('Name', (1, 1), 'None', ('Load',))])),
+('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])),
('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])),
('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
@@ -376,7 +565,10 @@
('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
('Expression', ('Name', (1, 0), 'v', ('Load',))),
('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
+('Expression', ('List', (1, 0), [], ('Load',))),
('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
+('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
+('Expression', ('Tuple', (1, 0), [], ('Load',))),
('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)),
]
main()
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 1d35a6a..ae3a67c 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -1683,6 +1683,7 @@
def _run_unittest(*args):
with check_py3k_warnings(
+ (".+ not supported in 3.1", DeprecationWarning),
(".+ not supported in 3.x", DeprecationWarning),
(".+ is renamed to imp.reload", DeprecationWarning),
("classic int division", DeprecationWarning)):
diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py
index d44a415..4885c8c 100644
--- a/Lib/test/test_cfgparser.py
+++ b/Lib/test/test_cfgparser.py
@@ -529,6 +529,27 @@
class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
allow_no_value = True
+class TestChainMap(unittest.TestCase):
+ def test_issue_12717(self):
+ d1 = dict(red=1, green=2)
+ d2 = dict(green=3, blue=4)
+ dcomb = d2.copy()
+ dcomb.update(d1)
+ cm = ConfigParser._Chainmap(d1, d2)
+ self.assertIsInstance(cm.keys(), list)
+ self.assertEqual(set(cm.keys()), set(dcomb.keys())) # keys()
+ self.assertEqual(set(cm.values()), set(dcomb.values())) # values()
+ self.assertEqual(set(cm.items()), set(dcomb.items())) # items()
+ self.assertEqual(set(cm), set(dcomb)) # __iter__ ()
+ self.assertEqual(cm, dcomb) # __eq__()
+ self.assertEqual([cm[k] for k in dcomb], dcomb.values()) # __getitem__()
+ klist = 'red green blue black brown'.split()
+ self.assertEqual([cm.get(k, 10) for k in klist],
+ [dcomb.get(k, 10) for k in klist]) # get()
+ self.assertEqual([k in cm for k in klist],
+ [k in dcomb for k in klist]) # __contains__()
+ self.assertEqual([cm.has_key(k) for k in klist],
+ [dcomb.has_key(k) for k in klist]) # has_key()
class Issue7005TestCase(unittest.TestCase):
"""Test output when None is set() as a value and allow_no_value == False.
@@ -591,6 +612,7 @@
SafeConfigParserTestCaseNoValue,
SortedTestCase,
Issue7005TestCase,
+ TestChainMap,
)
diff --git a/Lib/test/test_codecencodings_cn.py b/Lib/test/test_codecencodings_cn.py
index 96b0d77..215e8de 100644
--- a/Lib/test/test_codecencodings_cn.py
+++ b/Lib/test/test_codecencodings_cn.py
@@ -50,6 +50,35 @@
)
has_iso10646 = True
+class Test_HZ(test_multibytecodec_support.TestBase, unittest.TestCase):
+ encoding = 'hz'
+ tstring = test_multibytecodec_support.load_teststring('hz')
+ codectests = (
+ # test '~\n' (3 lines)
+ (b'This sentence is in ASCII.\n'
+ b'The next sentence is in GB.~{<:Ky2;S{#,~}~\n'
+ b'~{NpJ)l6HK!#~}Bye.\n',
+ 'strict',
+ u'This sentence is in ASCII.\n'
+ u'The next sentence is in GB.'
+ u'\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002'
+ u'Bye.\n'),
+ # test '~\n' (4 lines)
+ (b'This sentence is in ASCII.\n'
+ b'The next sentence is in GB.~\n'
+ b'~{<:Ky2;S{#,NpJ)l6HK!#~}~\n'
+ b'Bye.\n',
+ 'strict',
+ u'This sentence is in ASCII.\n'
+ u'The next sentence is in GB.'
+ u'\u5df1\u6240\u4e0d\u6b32\uff0c\u52ff\u65bd\u65bc\u4eba\u3002'
+ u'Bye.\n'),
+ # invalid bytes
+ (b'ab~cd', 'replace', u'ab\uFFFDd'),
+ (b'ab\xffcd', 'replace', u'ab\uFFFDcd'),
+ (b'ab~{\x81\x81\x41\x44~}cd', 'replace', u'ab\uFFFD\uFFFD\u804Acd'),
+ )
+
def test_main():
test_support.run_unittest(__name__)
diff --git a/Lib/test/test_codecencodings_iso2022.py b/Lib/test/test_codecencodings_iso2022.py
new file mode 100644
index 0000000..9d1d2af
--- /dev/null
+++ b/Lib/test/test_codecencodings_iso2022.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+#
+# Codec encoding tests for ISO 2022 encodings.
+
+from test import test_support
+from test import test_multibytecodec_support
+import unittest
+
+COMMON_CODEC_TESTS = (
+ # invalid bytes
+ (b'ab\xFFcd', 'replace', u'ab\uFFFDcd'),
+ (b'ab\x1Bdef', 'replace', u'ab\x1Bdef'),
+ (b'ab\x1B$def', 'replace', u'ab\uFFFD'),
+ )
+
+class Test_ISO2022_JP(test_multibytecodec_support.TestBase, unittest.TestCase):
+ encoding = 'iso2022_jp'
+ tstring = test_multibytecodec_support.load_teststring('iso2022_jp')
+ codectests = COMMON_CODEC_TESTS + (
+ (b'ab\x1BNdef', 'replace', u'ab\x1BNdef'),
+ )
+
+class Test_ISO2022_JP2(test_multibytecodec_support.TestBase, unittest.TestCase):
+ encoding = 'iso2022_jp_2'
+ tstring = test_multibytecodec_support.load_teststring('iso2022_jp')
+ codectests = COMMON_CODEC_TESTS + (
+ (b'ab\x1BNdef', 'replace', u'abdef'),
+ )
+
+class Test_ISO2022_KR(test_multibytecodec_support.TestBase, unittest.TestCase):
+ encoding = 'iso2022_kr'
+ tstring = test_multibytecodec_support.load_teststring('iso2022_kr')
+ codectests = COMMON_CODEC_TESTS + (
+ (b'ab\x1BNdef', 'replace', u'ab\x1BNdef'),
+ )
+
+ # iso2022_kr.txt cannot be used to test "chunk coding": the escape
+ # sequence is only written on the first line
+ def test_chunkcoding(self):
+ pass
+
+def test_main():
+ test_support.run_unittest(__name__)
+
+if __name__ == "__main__":
+ test_main()
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
index 7cd7141..d434f83 100644
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -1,6 +1,7 @@
from test import test_support
import unittest
import codecs
+import locale
import sys, StringIO, _testcapi
class Queue(object):
@@ -469,13 +470,11 @@
s1 = u'Hello\r\nworld\r\n'
s = s1.encode(self.encoding)
- try:
- with open(test_support.TESTFN, 'wb') as fp:
- fp.write(s)
- with codecs.open(test_support.TESTFN, 'U', encoding=self.encoding) as reader:
- self.assertEqual(reader.read(), s1)
- finally:
- test_support.unlink(test_support.TESTFN)
+ self.addCleanup(test_support.unlink, test_support.TESTFN)
+ with open(test_support.TESTFN, 'wb') as fp:
+ fp.write(s)
+ with codecs.open(test_support.TESTFN, 'U', encoding=self.encoding) as reader:
+ self.assertEqual(reader.read(), s1)
class UTF16LETest(ReadTest):
encoding = "utf-16-le"
@@ -1155,6 +1154,19 @@
self.assertRaises(TypeError, codecs.getwriter)
self.assertRaises(LookupError, codecs.getwriter, "__spam__")
+ def test_lookup_issue1813(self):
+ # Issue #1813: under Turkish locales, lookup of some codecs failed
+ # because 'I' is lowercased as a dotless "i"
+ oldlocale = locale.getlocale(locale.LC_CTYPE)
+ self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
+ try:
+ locale.setlocale(locale.LC_CTYPE, 'tr_TR')
+ except locale.Error:
+ # Unsupported locale on this system
+ self.skipTest('test needs Turkish locale')
+ c = codecs.lookup('ASCII')
+ self.assertEqual(c.name, 'ascii')
+
class StreamReaderTest(unittest.TestCase):
def setUp(self):
@@ -1532,6 +1544,7 @@
"utf-32",
"utf-32-le",
"utf-32-be")
+ self.addCleanup(test_support.unlink, test_support.TESTFN)
for encoding in tests:
# Check if the BOM is written only once
with codecs.open(test_support.TESTFN, 'w+', encoding=encoding) as f:
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index 8bdeb3d..313f81f 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -78,12 +78,12 @@
self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument
self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument
self.assertEqual(repr(p), 'Point(x=11, y=22)')
- self.assertNotIn('__dict__', dir(p)) # verify instance has no dict
self.assertNotIn('__weakref__', dir(p))
self.assertEqual(p, Point._make([11, 22])) # test _make classmethod
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
+ self.assertEqual(vars(p), p._asdict()) # verify that vars() works
try:
p._replace(x=1, error=2)
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index b5e86fb..964cc5c 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -1718,6 +1718,7 @@
("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
("__complex__", complex, complex_num, set(), {}),
("__format__", format, format_impl, set(), {}),
+ ("__dir__", dir, empty_seq, set(), {}),
]
class Checker(object):
@@ -4564,6 +4565,30 @@
with self.assertRaises(AttributeError):
del X.__abstractmethods__
+ def test_proxy_call(self):
+ class FakeStr(object):
+ __class__ = str
+
+ fake_str = FakeStr()
+ # isinstance() reads __class__ on new style classes
+ self.assertTrue(isinstance(fake_str, str))
+
+ # call a method descriptor
+ with self.assertRaises(TypeError):
+ str.split(fake_str)
+
+ # call a slot wrapper descriptor
+ with self.assertRaises(TypeError):
+ str.__add__(fake_str, "abc")
+
+ def test_repr_as_str(self):
+ # Issue #11603: crash or infinite loop when rebinding __str__ as
+ # __repr__.
+ class Foo(object):
+ pass
+ Foo.__repr__ = Foo.__str__
+ foo = Foo()
+ str(foo)
class DictProxyTests(unittest.TestCase):
def setUp(self):
@@ -4572,6 +4597,10 @@
pass
self.C = C
+ def test_repr(self):
+ self.assertIn('dict_proxy({', repr(vars(self.C)))
+ self.assertIn("'meth':", repr(vars(self.C)))
+
def test_iter_keys(self):
# Testing dict-proxy iterkeys...
keys = [ key for key in self.C.__dict__.iterkeys() ]
diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py
index a19c82d..5526fb7 100644
--- a/Lib/test/test_exceptions.py
+++ b/Lib/test/test_exceptions.py
@@ -464,6 +464,14 @@
self.assertTrue(e is RuntimeError, e)
self.assertIn("maximum recursion depth exceeded", str(v))
+ def test_new_returns_invalid_instance(self):
+ # See issue #11627.
+ class MyException(Exception):
+ def __new__(cls, *args):
+ return object()
+
+ with self.assertRaises(TypeError):
+ raise MyException
# Helper class used by TestSameStrAndUnicodeMsg
diff --git a/Lib/test/test_fcntl.py b/Lib/test/test_fcntl.py
index c8ea7b7..df09391 100644
--- a/Lib/test/test_fcntl.py
+++ b/Lib/test/test_fcntl.py
@@ -27,12 +27,8 @@
else:
start_len = "qq"
- if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3',
- 'Darwin1.2', 'darwin',
- 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
- 'freebsd6', 'freebsd7', 'freebsd8',
- 'bsdos2', 'bsdos3', 'bsdos4',
- 'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'):
+ if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 'bsdos'))
+ or sys.platform == 'darwin'):
if struct.calcsize('l') == 8:
off_t = 'l'
pid_t = 'i'
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
index ed41672..855ecbf 100644
--- a/Lib/test/test_hashlib.py
+++ b/Lib/test/test_hashlib.py
@@ -115,6 +115,24 @@
else:
self.assertTrue(0 == "hashlib didn't reject bogus hash name")
+ def test_get_builtin_constructor(self):
+ get_builtin_constructor = hashlib.__dict__[
+ '__get_builtin_constructor']
+ self.assertRaises(ValueError, get_builtin_constructor, 'test')
+ try:
+ import _md5
+ except ImportError:
+ pass
+ # This forces an ImportError for "import _md5" statements
+ sys.modules['_md5'] = None
+ try:
+ self.assertRaises(ValueError, get_builtin_constructor, 'md5')
+ finally:
+ if '_md5' in locals():
+ sys.modules['_md5'] = _md5
+ else:
+ del sys.modules['_md5']
+
def test_hexdigest(self):
for name in self.supported_hash_names:
h = hashlib.new(name)
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index d5d8c1a..5932a40 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -1,16 +1,31 @@
"""Unittests for heapq."""
-import random
-import unittest
-from test import test_support
import sys
+import random
-# We do a bit of trickery here to be able to test both the C implementation
-# and the Python implementation of the module.
-import heapq as c_heapq
+from test import test_support
+from unittest import TestCase, skipUnless
+
py_heapq = test_support.import_fresh_module('heapq', blocked=['_heapq'])
+c_heapq = test_support.import_fresh_module('heapq', fresh=['_heapq'])
-class TestHeap(unittest.TestCase):
+# _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when
+# _heapq is imported, so check them there
+func_names = ['heapify', 'heappop', 'heappush', 'heappushpop',
+ 'heapreplace', '_nlargest', '_nsmallest']
+
+class TestModules(TestCase):
+ def test_py_functions(self):
+ for fname in func_names:
+ self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq')
+
+ @skipUnless(c_heapq, 'requires _heapq')
+ def test_c_functions(self):
+ for fname in func_names:
+ self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
+
+
+class TestHeap(TestCase):
module = None
def test_push_pop(self):
@@ -175,21 +190,8 @@
self.assertEqual(self.module.nlargest(n, data, key=f),
sorted(data, key=f, reverse=True)[:n])
-class TestHeapPython(TestHeap):
- module = py_heapq
-
- # As an early adopter, we sanity check the
- # test_support.import_fresh_module utility function
- def test_pure_python(self):
- self.assertFalse(sys.modules['heapq'] is self.module)
- self.assertTrue(hasattr(self.module.heapify, 'func_code'))
-
-
-class TestHeapC(TestHeap):
- module = c_heapq
-
def test_comparison_operator(self):
- # Issue 3501: Make sure heapq works with both __lt__ and __le__
+ # Issue 3051: Make sure heapq works with both __lt__ and __le__
def hsort(data, comp):
data = map(comp, data)
self.module.heapify(data)
@@ -210,6 +212,15 @@
self.assertEqual(hsort(data, LE), target)
+class TestHeapPython(TestHeap):
+ module = py_heapq
+
+
+@skipUnless(c_heapq, 'requires _heapq')
+class TestHeapC(TestHeap):
+ module = c_heapq
+
+
#==============================================================================
class LenOnly:
@@ -304,9 +315,8 @@
'Test multiple tiers of iterators'
return chain(imap(lambda x:x, R(Ig(G(seqn)))))
-class TestErrorHandling(unittest.TestCase):
- # only for C implementation
- module = c_heapq
+class TestErrorHandling(TestCase):
+ module = None
def test_non_sequence(self):
for f in (self.module.heapify, self.module.heappop):
@@ -352,11 +362,21 @@
self.assertRaises(ZeroDivisionError, f, 2, E(s))
+class TestErrorHandlingPython(TestErrorHandling):
+ module = py_heapq
+
+
+@skipUnless(c_heapq, 'requires _heapq')
+class TestErrorHandlingC(TestErrorHandling):
+ module = c_heapq
+
+
#==============================================================================
def test_main(verbose=None):
- test_classes = [TestHeapPython, TestHeapC, TestErrorHandling]
+ test_classes = [TestModules, TestHeapPython, TestHeapC,
+ TestErrorHandlingPython, TestErrorHandlingC]
test_support.run_unittest(*test_classes)
# verify reference counting
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
index 5751901..f654c33 100644
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -265,6 +265,14 @@
"""))
script_helper.assert_python_ok(testfn)
+ def test_bug7732(self):
+ source = TESTFN + '.py'
+ os.mkdir(source)
+ try:
+ self.assertRaises(IOError, imp.find_module, TESTFN, ["."])
+ finally:
+ os.rmdir(source)
+
class PycRewritingTests(unittest.TestCase):
# Test that the `co_filename` attribute on code objects always points
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index d93ffec..b8c9a18 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -295,6 +295,23 @@
del sys.modules[name]
inspect.getmodule(compile('a=10','','single'))
+ def test_proceed_with_fake_filename(self):
+ '''doctest monkeypatches linecache to enable inspection'''
+ fn, source = '<test>', 'def x(): pass\n'
+ getlines = linecache.getlines
+ def monkey(filename, module_globals=None):
+ if filename == fn:
+ return source.splitlines(True)
+ else:
+ return getlines(filename, module_globals)
+ linecache.getlines = monkey
+ try:
+ ns = {}
+ exec compile(source, fn, 'single') in ns
+ inspect.getsource(ns["x"])
+ finally:
+ linecache.getlines = getlines
+
class TestDecorators(GetSourceBase):
fodderFile = mod2
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 0bad56d..003a4f3 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -585,7 +585,24 @@
self.assertEqual(rawio.read(2), b"")
class CIOTest(IOTest):
- pass
+
+ def test_IOBase_finalize(self):
+ # Issue #12149: segmentation fault on _PyIOBase_finalize when both a
+ # class which inherits IOBase and an object of this class are caught
+ # in a reference cycle and close() is already in the method cache.
+ class MyIO(self.IOBase):
+ def close(self):
+ pass
+
+ # create an instance to populate the method cache
+ MyIO()
+ obj = MyIO()
+ obj.obj = obj
+ wr = weakref.ref(obj)
+ del MyIO
+ del obj
+ support.gc_collect()
+ self.assertTrue(wr() is None, wr)
class PyIOTest(IOTest):
test_array_writes = unittest.skip(
@@ -798,14 +815,17 @@
# Inject some None's in there to simulate EWOULDBLOCK
rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None))
bufio = self.tp(rawio)
-
self.assertEqual(b"abcd", bufio.read(6))
self.assertEqual(b"e", bufio.read(1))
self.assertEqual(b"fg", bufio.read())
self.assertEqual(b"", bufio.peek(1))
- self.assertTrue(None is bufio.read())
+ self.assertIsNone(bufio.read())
self.assertEqual(b"", bufio.read())
+ rawio = self.MockRawIO((b"a", None, None))
+ self.assertEqual(b"a", rawio.readall())
+ self.assertIsNone(rawio.readall())
+
def test_read_past_eof(self):
rawio = self.MockRawIO((b"abc", b"d", b"efg"))
bufio = self.tp(rawio)
@@ -1347,15 +1367,18 @@
rw.seek(0, 0)
self.assertEqual(b"asdf", rw.read(4))
- rw.write(b"asdf")
+ rw.write(b"123f")
rw.seek(0, 0)
- self.assertEqual(b"asdfasdfl", rw.read())
+ self.assertEqual(b"asdf123fl", rw.read())
self.assertEqual(9, rw.tell())
rw.seek(-4, 2)
self.assertEqual(5, rw.tell())
rw.seek(2, 1)
self.assertEqual(7, rw.tell())
self.assertEqual(b"fl", rw.read(11))
+ rw.flush()
+ self.assertEqual(b"asdf123fl", raw.getvalue())
+
self.assertRaises(TypeError, rw.seek, 0.0)
def check_flush_and_read(self, read_func):
@@ -1462,6 +1485,32 @@
self.assertEqual(s,
b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size))
+ def test_write_rewind_write(self):
+ # Various combinations of reading / writing / seeking backwards / writing again
+ def mutate(bufio, pos1, pos2):
+ assert pos2 >= pos1
+ # Fill the buffer
+ bufio.seek(pos1)
+ bufio.read(pos2 - pos1)
+ bufio.write(b'\x02')
+ # This writes earlier than the previous write, but still inside
+ # the buffer.
+ bufio.seek(pos1)
+ bufio.write(b'\x01')
+
+ b = b"\x80\x81\x82\x83\x84"
+ for i in range(0, len(b)):
+ for j in range(i, len(b)):
+ raw = self.BytesIO(b)
+ bufio = self.tp(raw, 100)
+ mutate(bufio, i, j)
+ bufio.flush()
+ expected = bytearray(b)
+ expected[j] = 2
+ expected[i] = 1
+ self.assertEqual(raw.getvalue(), expected,
+ "failed result for i=%d, j=%d" % (i, j))
+
def test_truncate_after_read_or_write(self):
raw = self.BytesIO(b"A" * 10)
bufio = self.tp(raw, 100)
@@ -1474,6 +1523,44 @@
BufferedReaderTest.test_misbehaved_io(self)
BufferedWriterTest.test_misbehaved_io(self)
+ def test_interleaved_read_write(self):
+ # Test for issue #12213
+ with self.BytesIO(b'abcdefgh') as raw:
+ with self.tp(raw, 100) as f:
+ f.write(b"1")
+ self.assertEqual(f.read(1), b'b')
+ f.write(b'2')
+ self.assertEqual(f.read1(1), b'd')
+ f.write(b'3')
+ buf = bytearray(1)
+ f.readinto(buf)
+ self.assertEqual(buf, b'f')
+ f.write(b'4')
+ self.assertEqual(f.peek(1), b'h')
+ f.flush()
+ self.assertEqual(raw.getvalue(), b'1b2d3f4h')
+
+ with self.BytesIO(b'abc') as raw:
+ with self.tp(raw, 100) as f:
+ self.assertEqual(f.read(1), b'a')
+ f.write(b"2")
+ self.assertEqual(f.read(1), b'c')
+ f.flush()
+ self.assertEqual(raw.getvalue(), b'a2c')
+
+ def test_interleaved_readline_write(self):
+ with self.BytesIO(b'ab\ncdef\ng\n') as raw:
+ with self.tp(raw) as f:
+ f.write(b'1')
+ self.assertEqual(f.readline(), b'b\n')
+ f.write(b'2')
+ self.assertEqual(f.readline(), b'def\n')
+ f.write(b'3')
+ self.assertEqual(f.readline(), b'\n')
+ f.flush()
+ self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n')
+
+
class CBufferedRandomTest(CBufferedReaderTest, CBufferedWriterTest, BufferedRandomTest):
tp = io.BufferedRandom
@@ -2251,6 +2338,21 @@
with self.open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"456def")
+ def test_rwpair_cleared_before_textio(self):
+ # Issue 13070: TextIOWrapper's finalization would crash when called
+ # after the reference to the underlying BufferedRWPair's writer got
+ # cleared by the GC.
+ for i in range(1000):
+ b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
+ t1 = self.TextIOWrapper(b1, encoding="ascii")
+ b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
+ t2 = self.TextIOWrapper(b2, encoding="ascii")
+ # circular references
+ t1.buddy = t2
+ t2.buddy = t1
+ support.gc_collect()
+
+
class PyTextIOWrapperTest(TextIOWrapperTest):
pass
@@ -2442,6 +2544,8 @@
self.assertRaises(ValueError, f.read)
if hasattr(f, "read1"):
self.assertRaises(ValueError, f.read1, 1024)
+ if hasattr(f, "readall"):
+ self.assertRaises(ValueError, f.readall)
if hasattr(f, "readinto"):
self.assertRaises(ValueError, f.readinto, bytearray(1024))
self.assertRaises(ValueError, f.readline)
@@ -2526,6 +2630,8 @@
1 // 0
@unittest.skipUnless(threading, 'Threading required for this test.')
+ @unittest.skipIf(sys.platform in ('freebsd5', 'freebsd6', 'freebsd7'),
+ 'issue #12429: skip test on FreeBSD <= 7')
def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
"""Check that a partial write, when it gets interrupted, properly
invokes the signal handler, and bubbles up the exception raised
@@ -2579,7 +2685,7 @@
def on_alarm(*args):
# Will be called reentrantly from the same thread
wio.write(data)
- 1/0
+ 1//0
signal.signal(signal.SIGALRM, on_alarm)
r, w = os.pipe()
wio = self.io.open(w, **fdopen_kwargs)
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 97feb7b..ccdbf8a 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -137,7 +137,8 @@
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 implementation detail: tuple re-use
+ @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)
self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
@@ -207,7 +208,9 @@
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 implementation detail: tuple re-use
+ @test_support.impl_detail("tuple reuse is specific to CPython")
+ def test_combinations_with_replacement_tuple_reuse(self):
+ cwr = combinations_with_replacement
self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
@@ -271,7 +274,8 @@
self.assertEqual(result, list(permutations(values, None))) # test r as None
self.assertEqual(result, list(permutations(values))) # test default r
- # Test implementation detail: tuple re-use
+ @test_support.impl_detail("tuple resuse is CPython specific")
+ def test_permutations_tuple_reuse(self):
self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
@@ -526,11 +530,13 @@
self.assertEqual(list(izip()), zip())
self.assertRaises(TypeError, izip, 3)
self.assertRaises(TypeError, izip, range(3), 3)
- # Check tuple re-use (implementation detail)
self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
zip('abc', 'def'))
self.assertEqual([pair for pair in izip('abc', 'def')],
zip('abc', 'def'))
+
+ @test_support.impl_detail("tuple reuse is specific to CPython")
+ def test_izip_tuple_resuse(self):
ids = map(id, izip('abc', 'def'))
self.assertEqual(min(ids), max(ids))
ids = map(id, list(izip('abc', 'def')))
@@ -575,11 +581,13 @@
else:
self.fail('Did not raise Type in: ' + stmt)
- # Check tuple re-use (implementation detail)
self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
zip('abc', 'def'))
self.assertEqual([pair for pair in izip_longest('abc', 'def')],
zip('abc', 'def'))
+
+ @test_support.impl_detail("tuple reuse is specific to CPython")
+ def test_izip_longest_tuple_reuse(self):
ids = map(id, izip_longest('abc', 'def'))
self.assertEqual(min(ids), max(ids))
ids = map(id, list(izip_longest('abc', 'def')))
@@ -683,7 +691,8 @@
args = map(iter, args)
self.assertEqual(len(list(product(*args))), expected_len)
- # Test implementation detail: tuple re-use
+ @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)
self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
diff --git a/Lib/test/test_linecache.py b/Lib/test/test_linecache.py
index 407bebc..b5f80a4 100644
--- a/Lib/test/test_linecache.py
+++ b/Lib/test/test_linecache.py
@@ -9,7 +9,7 @@
FILENAME = linecache.__file__
INVALID_NAME = '!@$)(!@#_1'
EMPTY = ''
-TESTS = 'cjkencodings_test inspect_fodder inspect_fodder2 mapping_tests'
+TESTS = 'inspect_fodder inspect_fodder2 mapping_tests'
TESTS = TESTS.split()
TEST_PATH = os.path.dirname(support.__file__)
MODULES = "linecache abc".split()
diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py
index 8bb99cb..a88d34b 100644
--- a/Lib/test/test_locale.py
+++ b/Lib/test/test_locale.py
@@ -1,4 +1,5 @@
from test.test_support import run_unittest, verbose
+from platform import linux_distribution
import unittest
import locale
import sys
@@ -396,6 +397,26 @@
# crasher from bug #7419
self.assertRaises(locale.Error, locale.setlocale, 12345)
+ @unittest.skipIf(linux_distribution()[0] == 'Fedora', "Fedora setlocale() "
+ "bug: https://bugzilla.redhat.com/show_bug.cgi?id=726536")
+ def test_getsetlocale_issue1813(self):
+ # Issue #1813: setting and getting the locale under a Turkish locale
+ oldlocale = locale.getlocale()
+ self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
+ try:
+ locale.setlocale(locale.LC_CTYPE, 'tr_TR')
+ except locale.Error:
+ # Unsupported locale on this system
+ self.skipTest('test needs Turkish locale')
+ loc = locale.getlocale()
+ locale.setlocale(locale.LC_CTYPE, loc)
+ self.assertEqual(loc, locale.getlocale())
+
+ def test_normalize_issue12752(self):
+ # Issue #1813 caused a regression where locale.normalize() would no
+ # longer accept unicode strings.
+ self.assertEqual(locale.normalize(u'en_US'), 'en_US.ISO8859-1')
+
def test_main():
tests = [
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
index 83e3132..1124979 100644
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -174,6 +174,13 @@
self.assertEqual(self._box.get_file(key1).read().replace(os.linesep, '\n'),
_sample_message)
+ def test_get_file_can_be_closed_twice(self):
+ # Issue 11700
+ key = self._box.add(_sample_message)
+ f = self._box.get_file(key)
+ f.close()
+ f.close()
+
def test_iterkeys(self):
# Get keys using iterkeys()
self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False)
@@ -751,27 +758,28 @@
self.assertFalse((perms & 0111)) # Execute bits should all be off.
def test_reread(self):
- # Wait for 2 seconds
- time.sleep(2)
- # Initially, the mailbox has not been read and the time is null.
- assert getattr(self._box, '_last_read', None) is None
+ # Put the last modified times more than two seconds into the past
+ # (because mtime may have only a two second granularity).
+ for subdir in ('cur', 'new'):
+ os.utime(os.path.join(self._box._path, subdir),
+ (time.time()-5,)*2)
- # Refresh mailbox; the times should now be set to something.
- self._box._refresh()
- assert getattr(self._box, '_last_read', None) is not None
+ # Because mtime has a two second granularity in worst case (FAT), a
+ # refresh is done unconditionally if called for within
+ # two-second-plus-a-bit of the last one, just in case the mbox has
+ # changed; so now we have to wait for that interval to expire.
+ time.sleep(2.01 + self._box._skewfactor)
- # Try calling _refresh() again; the modification times shouldn't have
- # changed, so the mailbox should not be re-reading. Re-reading causes
- # the ._toc attribute to be assigned a new dictionary object, so
- # we'll check that the ._toc attribute isn't a different object.
+ # Re-reading causes the ._toc attribute to be assigned a new dictionary
+ # object, so we'll check that the ._toc attribute isn't a different
+ # object.
orig_toc = self._box._toc
def refreshed():
return self._box._toc is not orig_toc
- time.sleep(1) # Wait 1sec to ensure time.time()'s value changes
self._box._refresh()
- assert not refreshed()
+ self.assertFalse(refreshed())
# Now, write something into cur and remove it. This changes
# the mtime and should cause a re-read.
@@ -780,7 +788,7 @@
f.close()
os.unlink(filename)
self._box._refresh()
- assert refreshed()
+ self.assertTrue(refreshed())
class _TestMboxMMDF(TestMailbox):
@@ -1669,7 +1677,8 @@
def _test_close(self, proxy):
# Close a file
proxy.close()
- self.assertRaises(AttributeError, lambda: proxy.close())
+ # Issue 11700 subsequent closes should be a no-op, not an error.
+ proxy.close()
class TestProxyFile(TestProxyFileBase):
diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index efb9240..cb1c60c 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -46,26 +46,6 @@
return doc
class MinidomTest(unittest.TestCase):
- def tearDown(self):
- try:
- Node.allnodes
- except AttributeError:
- # We don't actually have the minidom from the standard library,
- # but are picking up the PyXML version from site-packages.
- pass
- else:
- self.confirm(len(Node.allnodes) == 0,
- "assertion: len(Node.allnodes) == 0")
- if len(Node.allnodes):
- print "Garbage left over:"
- if verbose:
- print Node.allnodes.items()[0:10]
- else:
- # Don't print specific nodes if repeatable results
- # are needed
- print len(Node.allnodes)
- Node.allnodes = {}
-
def confirm(self, test, testname = "Test"):
self.assertTrue(test, testname)
@@ -459,6 +439,13 @@
dom.unlink()
self.confirm(domstr == str.replace("\n", "\r\n"))
+ def test_toprettyxml_preserves_content_of_text_node(self):
+ str = '<A>B</A>'
+ dom = parseString(str)
+ dom2 = parseString(dom.toprettyxml())
+ self.assertEqual(dom.childNodes[0].childNodes[0].toxml(),
+ dom2.childNodes[0].childNodes[0].toxml())
+
def testProcessingInstruction(self):
dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
pi = dom.documentElement.firstChild
diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py
index 62c6983..2c2863e 100644
--- a/Lib/test/test_mmap.py
+++ b/Lib/test/test_mmap.py
@@ -1,4 +1,5 @@
-from test.test_support import TESTFN, run_unittest, import_module, unlink, requires
+from test.test_support import (TESTFN, run_unittest, import_module, unlink,
+ requires, _2G, _4G)
import unittest
import os, re, itertools, socket, sys
@@ -644,29 +645,22 @@
def tearDown(self):
unlink(TESTFN)
- def _working_largefile(self):
- # Only run if the current filesystem supports large files.
- f = open(TESTFN, 'wb', buffering=0)
- try:
- f.seek(0x80000001)
- f.write(b'x')
- f.flush()
- except (IOError, OverflowError):
- raise unittest.SkipTest("filesystem does not have largefile support")
- finally:
- f.close()
- unlink(TESTFN)
-
- def test_large_offset(self):
+ def _make_test_file(self, num_zeroes, tail):
if sys.platform[:3] == 'win' or sys.platform == 'darwin':
requires('largefile',
'test requires %s bytes and a long time to run' % str(0x180000000))
- self._working_largefile()
- with open(TESTFN, 'wb') as f:
- f.seek(0x14FFFFFFF)
- f.write(b" ")
+ f = open(TESTFN, 'w+b')
+ try:
+ f.seek(num_zeroes)
+ f.write(tail)
+ f.flush()
+ except (IOError, OverflowError):
+ f.close()
+ raise unittest.SkipTest("filesystem does not have largefile support")
+ return f
- with open(TESTFN, 'rb') as f:
+ def test_large_offset(self):
+ with self._make_test_file(0x14FFFFFFF, b" ") as f:
m = mmap.mmap(f.fileno(), 0, offset=0x140000000, access=mmap.ACCESS_READ)
try:
self.assertEqual(m[0xFFFFFFF], b" ")
@@ -674,21 +668,34 @@
m.close()
def test_large_filesize(self):
- if sys.platform[:3] == 'win' or sys.platform == 'darwin':
- requires('largefile',
- 'test requires %s bytes and a long time to run' % str(0x180000000))
- self._working_largefile()
- with open(TESTFN, 'wb') as f:
- f.seek(0x17FFFFFFF)
- f.write(b" ")
-
- with open(TESTFN, 'rb') as f:
+ with self._make_test_file(0x17FFFFFFF, b" ") as f:
m = mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ)
try:
self.assertEqual(m.size(), 0x180000000)
finally:
m.close()
+ # Issue 11277: mmap() with large (~4GB) sparse files crashes on OS X.
+
+ def _test_around_boundary(self, boundary):
+ tail = b' DEARdear '
+ start = boundary - len(tail) // 2
+ end = start + len(tail)
+ with self._make_test_file(start, tail) as f:
+ m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
+ try:
+ self.assertEqual(m[start:end], tail)
+ finally:
+ m.close()
+
+ @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
+ def test_around_2GB(self):
+ self._test_around_boundary(_2G)
+
+ @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
+ def test_around_4GB(self):
+ self._test_around_boundary(_4G)
+
def test_main():
run_unittest(MmapTests, LargeMmapTests)
diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py
index 63c1e62..5e86ca2 100644
--- a/Lib/test/test_multibytecodec.py
+++ b/Lib/test/test_multibytecodec.py
@@ -237,6 +237,36 @@
# Any ISO 2022 codec will cause the segfault
myunichr(x).encode('iso_2022_jp', 'ignore')
+class TestStateful(unittest.TestCase):
+ text = u'\u4E16\u4E16'
+ encoding = 'iso-2022-jp'
+ expected = b'\x1b$B@$@$'
+ expected_reset = b'\x1b$B@$@$\x1b(B'
+
+ def test_encode(self):
+ self.assertEqual(self.text.encode(self.encoding), self.expected_reset)
+
+ def test_incrementalencoder(self):
+ encoder = codecs.getincrementalencoder(self.encoding)()
+ output = b''.join(
+ encoder.encode(char)
+ for char in self.text)
+ self.assertEqual(output, self.expected)
+
+ def test_incrementalencoder_final(self):
+ encoder = codecs.getincrementalencoder(self.encoding)()
+ last_index = len(self.text) - 1
+ output = b''.join(
+ encoder.encode(char, index == last_index)
+ for index, char in enumerate(self.text))
+ self.assertEqual(output, self.expected_reset)
+
+class TestHZStateful(TestStateful):
+ text = u'\u804a\u804a'
+ encoding = 'hz'
+ expected = b'~{ADAD'
+ expected_reset = b'~{ADAD~}'
+
def test_main():
test_support.run_unittest(__name__)
diff --git a/Lib/test/test_multibytecodec_support.py b/Lib/test/test_multibytecodec_support.py
index 0639032..52a2e50 100644
--- a/Lib/test/test_multibytecodec_support.py
+++ b/Lib/test/test_multibytecodec_support.py
@@ -4,8 +4,11 @@
# Common Unittest Routines for CJK codecs
#
-import sys, codecs
-import unittest, re
+import codecs
+import os
+import re
+import sys
+import unittest
from httplib import HTTPException
from test import test_support
from StringIO import StringIO
@@ -41,13 +44,24 @@
def test_errorhandle(self):
for source, scheme, expected in self.codectests:
- if type(source) == type(''):
+ if isinstance(source, bytes):
func = self.decode
else:
func = self.encode
if expected:
result = func(source, scheme)[0]
- self.assertEqual(result, expected)
+ if func is self.decode:
+ self.assertTrue(type(result) is unicode, type(result))
+ self.assertEqual(result, expected,
+ '%r.decode(%r, %r)=%r != %r'
+ % (source, self.encoding, scheme, result,
+ expected))
+ else:
+ self.assertTrue(type(result) is bytes, type(result))
+ self.assertEqual(result, expected,
+ '%r.encode(%r, %r)=%r != %r'
+ % (source, self.encoding, scheme, result,
+ expected))
else:
self.assertRaises(UnicodeError, func, source, scheme)
@@ -248,6 +262,7 @@
pass_enctest = []
pass_dectest = []
supmaps = []
+ codectests = []
def __init__(self, *args, **kw):
unittest.TestCase.__init__(self, *args, **kw)
@@ -326,6 +341,34 @@
self.fail('Decoding failed while testing %s -> %s: %s' % (
repr(csetch), repr(unich), exc.reason))
-def load_teststring(encoding):
- from test import cjkencodings_test
- return cjkencodings_test.teststring[encoding]
+ def test_errorhandle(self):
+ for source, scheme, expected in self.codectests:
+ if isinstance(source, bytes):
+ func = source.decode
+ else:
+ func = source.encode
+ if expected:
+ if isinstance(source, bytes):
+ result = func(self.encoding, scheme)
+ self.assertTrue(type(result) is unicode, type(result))
+ self.assertEqual(result, expected,
+ '%r.decode(%r, %r)=%r != %r'
+ % (source, self.encoding, scheme, result,
+ expected))
+ else:
+ result = func(self.encoding, scheme)
+ self.assertTrue(type(result) is bytes, type(result))
+ self.assertEqual(result, expected,
+ '%r.encode(%r, %r)=%r != %r'
+ % (source, self.encoding, scheme, result,
+ expected))
+ else:
+ self.assertRaises(UnicodeError, func, self.encoding, scheme)
+
+def load_teststring(name):
+ dir = os.path.join(os.path.dirname(__file__), 'cjkencodings')
+ with open(os.path.join(dir, name + '.txt'), 'rb') as f:
+ encoded = f.read()
+ with open(os.path.join(dir, name + '-utf8.txt'), 'rb') as f:
+ utf8 = f.read()
+ return encoded, utf8
diff --git a/Lib/test/test_multiprocessing.py b/Lib/test/test_multiprocessing.py
index fe19de0..201fa98 100644
--- a/Lib/test/test_multiprocessing.py
+++ b/Lib/test/test_multiprocessing.py
@@ -15,6 +15,7 @@
import socket
import random
import logging
+import errno
from test import test_support
from StringIO import StringIO
_multiprocessing = test_support.import_module('_multiprocessing')
@@ -35,11 +36,22 @@
from multiprocessing import util
try:
+ from multiprocessing import reduction
+ HAS_REDUCTION = True
+except ImportError:
+ HAS_REDUCTION = False
+
+try:
from multiprocessing.sharedctypes import Value, copy
HAS_SHAREDCTYPES = True
except ImportError:
HAS_SHAREDCTYPES = False
+try:
+ import msvcrt
+except ImportError:
+ msvcrt = None
+
#
#
#
@@ -68,6 +80,11 @@
WIN32 = (sys.platform == "win32")
+try:
+ MAXFD = os.sysconf("SC_OPEN_MAX")
+except:
+ MAXFD = 256
+
#
# Some tests require ctypes
#
@@ -253,6 +270,7 @@
p = self.Process(target=time.sleep, args=(DELTA,))
self.assertNotIn(p, self.active_children())
+ p.daemon = True
p.start()
self.assertIn(p, self.active_children())
@@ -323,6 +341,7 @@
def test_subclassing(self):
uppercaser = _UpperCaser()
+ uppercaser.daemon = True
uppercaser.start()
self.assertEqual(uppercaser.submit('hello'), 'HELLO')
self.assertEqual(uppercaser.submit('world'), 'WORLD')
@@ -501,6 +520,7 @@
# fork process
p = self.Process(target=self._test_fork, args=(queue,))
+ p.daemon = True
p.start()
# check that all expected items are in the queue
@@ -541,6 +561,7 @@
for i in xrange(4)]
for p in workers:
+ p.daemon = True
p.start()
for i in xrange(10):
@@ -805,7 +826,9 @@
#self.assertEqual(event.is_set(), False)
- self.Process(target=self._test_event, args=(event,)).start()
+ p = self.Process(target=self._test_event, args=(event,))
+ p.daemon = True
+ p.start()
self.assertEqual(wait(), True)
#
@@ -845,6 +868,7 @@
self.assertEqual(sv.value, cv[1])
proc = self.Process(target=self._test, args=(values,))
+ proc.daemon = True
proc.start()
proc.join()
@@ -908,6 +932,7 @@
self.f(seq)
p = self.Process(target=self.f, args=(arr,))
+ p.daemon = True
p.start()
p.join()
@@ -1085,6 +1110,9 @@
self.assertEqual(sorted(it), map(sqr, range(1000)))
def test_make_pool(self):
+ self.assertRaises(ValueError, multiprocessing.Pool, -1)
+ self.assertRaises(ValueError, multiprocessing.Pool, 0)
+
p = multiprocessing.Pool(3)
self.assertEqual(3, len(p._pool))
p.close()
@@ -1271,6 +1299,7 @@
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
+ p.daemon = True
p.start()
manager2 = QueueManager2(
@@ -1312,6 +1341,7 @@
manager.start()
p = self.Process(target=self._putter, args=(manager.address, authkey))
+ p.daemon = True
p.start()
queue = manager.get_queue()
self.assertEqual(queue.get(), 'hello world')
@@ -1435,6 +1465,7 @@
conn, child_conn = self.Pipe()
p = self.Process(target=self._echo, args=(child_conn,))
+ p.daemon = True
p.start()
child_conn.close() # this might complete before child initializes
@@ -1478,6 +1509,98 @@
self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
+ @classmethod
+ def _is_fd_assigned(cls, fd):
+ try:
+ os.fstat(fd)
+ except OSError as e:
+ if e.errno == errno.EBADF:
+ return False
+ raise
+ else:
+ return True
+
+ @classmethod
+ def _writefd(cls, conn, data, create_dummy_fds=False):
+ if create_dummy_fds:
+ for i in range(0, 256):
+ if not cls._is_fd_assigned(i):
+ os.dup2(conn.fileno(), i)
+ fd = reduction.recv_handle(conn)
+ if msvcrt:
+ fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
+ os.write(fd, data)
+ os.close(fd)
+
+ @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
+ def test_fd_transfer(self):
+ if self.TYPE != 'processes':
+ self.skipTest("only makes sense with processes")
+ conn, child_conn = self.Pipe(duplex=True)
+
+ p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
+ p.daemon = True
+ p.start()
+ with open(test_support.TESTFN, "wb") as f:
+ fd = f.fileno()
+ if msvcrt:
+ fd = msvcrt.get_osfhandle(fd)
+ reduction.send_handle(conn, fd, p.pid)
+ p.join()
+ with open(test_support.TESTFN, "rb") as f:
+ self.assertEqual(f.read(), b"foo")
+
+ @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
+ @unittest.skipIf(sys.platform == "win32",
+ "test semantics don't make sense on Windows")
+ @unittest.skipIf(MAXFD <= 256,
+ "largest assignable fd number is too small")
+ @unittest.skipUnless(hasattr(os, "dup2"),
+ "test needs os.dup2()")
+ def test_large_fd_transfer(self):
+ # With fd > 256 (issue #11657)
+ if self.TYPE != 'processes':
+ self.skipTest("only makes sense with processes")
+ conn, child_conn = self.Pipe(duplex=True)
+
+ p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
+ p.daemon = True
+ p.start()
+ with open(test_support.TESTFN, "wb") as f:
+ fd = f.fileno()
+ for newfd in range(256, MAXFD):
+ if not self._is_fd_assigned(newfd):
+ break
+ else:
+ self.fail("could not find an unassigned large file descriptor")
+ os.dup2(fd, newfd)
+ try:
+ reduction.send_handle(conn, newfd, p.pid)
+ finally:
+ os.close(newfd)
+ p.join()
+ with open(test_support.TESTFN, "rb") as f:
+ self.assertEqual(f.read(), b"bar")
+
+ @classmethod
+ def _send_data_without_fd(self, conn):
+ os.write(conn.fileno(), b"\0")
+
+ @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
+ @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
+ def test_missing_fd_transfer(self):
+ # Check that exception is raised when received data is not
+ # accompanied by a file descriptor in ancillary data.
+ if self.TYPE != 'processes':
+ self.skipTest("only makes sense with processes")
+ conn, child_conn = self.Pipe(duplex=True)
+
+ p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
+ p.daemon = True
+ p.start()
+ self.assertRaises(RuntimeError, reduction.recv_handle, conn)
+ p.join()
+
class _TestListenerClient(BaseTestCase):
ALLOWED_TYPES = ('processes', 'threads')
@@ -1548,11 +1671,13 @@
lconn, lconn0 = self.Pipe()
lp = self.Process(target=self._listener, args=(lconn0, families))
+ lp.daemon = True
lp.start()
lconn0.close()
rconn, rconn0 = self.Pipe()
rp = self.Process(target=self._remote, args=(rconn0,))
+ rp.daemon = True
rp.start()
rconn0.close()
@@ -1612,6 +1737,8 @@
# verify the state of the heap
all = []
occupied = 0
+ heap._lock.acquire()
+ self.addCleanup(heap._lock.release)
for L in heap._len_to_seq.values():
for arena, start, stop in L:
all.append((heap._arenas.index(arena), start, stop,
@@ -1629,6 +1756,28 @@
self.assertTrue((arena != narena and nstart == 0) or
(stop == nstart))
+ def test_free_from_gc(self):
+ # Check that freeing of blocks by the garbage collector doesn't deadlock
+ # (issue #12352).
+ # Make sure the GC is enabled, and set lower collection thresholds to
+ # make collections more frequent (and increase the probability of
+ # deadlock).
+ if not gc.isenabled():
+ gc.enable()
+ self.addCleanup(gc.disable)
+ thresholds = gc.get_threshold()
+ self.addCleanup(gc.set_threshold, *thresholds)
+ gc.set_threshold(10)
+
+ # perform numerous block allocations, with cyclic references to make
+ # sure objects are collected asynchronously by the gc
+ for i in range(5000):
+ a = multiprocessing.heap.BufferWrapper(1)
+ b = multiprocessing.heap.BufferWrapper(1)
+ # circular references
+ a.buddy = b
+ b.buddy = a
+
#
#
#
@@ -1666,6 +1815,7 @@
string.value = latin('hello')
p = self.Process(target=self._double, args=(x, y, foo, arr, string))
+ p.daemon = True
p.start()
p.join()
@@ -1738,6 +1888,7 @@
conn, child_conn = self.Pipe()
p = self.Process(target=self._test_finalize, args=(child_conn,))
+ p.daemon = True
p.start()
p.join()
@@ -1757,10 +1908,12 @@
'multiprocessing', 'multiprocessing.connection',
'multiprocessing.heap', 'multiprocessing.managers',
'multiprocessing.pool', 'multiprocessing.process',
- 'multiprocessing.reduction',
'multiprocessing.synchronize', 'multiprocessing.util'
]
+ if HAS_REDUCTION:
+ modules.append('multiprocessing.reduction')
+
if c_int is not None:
# This module requires _ctypes
modules.append('multiprocessing.sharedctypes')
@@ -1807,12 +1960,16 @@
reader, writer = multiprocessing.Pipe(duplex=False)
logger.setLevel(LEVEL1)
- self.Process(target=self._test_level, args=(writer,)).start()
+ p = self.Process(target=self._test_level, args=(writer,))
+ p.daemon = True
+ p.start()
self.assertEqual(LEVEL1, reader.recv())
logger.setLevel(logging.NOTSET)
root_logger.setLevel(LEVEL2)
- self.Process(target=self._test_level, args=(writer,)).start()
+ p = self.Process(target=self._test_level, args=(writer,))
+ p.daemon = True
+ p.start()
self.assertEqual(LEVEL2, reader.recv())
root_logger.setLevel(root_level)
@@ -1998,6 +2155,7 @@
def _TestProcess(q):
queue = multiprocessing.Queue()
subProc = multiprocessing.Process(target=_ThisSubProcess, args=(queue,))
+ subProc.daemon = True
subProc.start()
subProc.join()
diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py
index a988430..2795456 100644
--- a/Lib/test/test_netrc.py
+++ b/Lib/test/test_netrc.py
@@ -1,54 +1,107 @@
-
-import netrc, os, unittest, sys
+import netrc, os, unittest, sys, textwrap
from test import test_support
-TEST_NETRC = """
-
- #this is a comment
-#this is a comment
-# this is a comment
-
-machine foo login log1 password pass1 account acct1
-machine bar login log1 password pass# account acct1
-
-macdef macro1
-line1
-line2
-
-macdef macro2
-line3
-line4
-
-default login log2 password pass2
-
-"""
-
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):
- def setUp (self):
- mode = 'w'
- if sys.platform not in ['cygwin']:
- mode += 't'
- fp = open(temp_filename, mode)
- fp.write(TEST_NETRC)
- fp.close()
- self.nrc = netrc.netrc(temp_filename)
-
- def tearDown (self):
+ def tearDown(self):
os.unlink(temp_filename)
- def test_case_1(self):
- self.assertEqual(self.nrc.hosts['foo'], ('log1', 'acct1', 'pass1'))
- self.assertEqual(self.nrc.hosts['default'], ('log2', None, 'pass2'))
+ def make_nrc(self, test_data):
+ test_data = textwrap.dedent(test_data)
+ mode = 'w'
+ if sys.platform != 'cygwin':
+ mode += 't'
+ with open(temp_filename, mode) as fp:
+ fp.write(test_data)
+ return netrc.netrc(temp_filename)
+
+ def test_default(self):
+ nrc = self.make_nrc("""\
+ machine host1.domain.com login log1 password pass1 account acct1
+ default login log2 password pass2
+ """)
+ self.assertEqual(nrc.hosts['host1.domain.com'],
+ ('log1', 'acct1', 'pass1'))
+ self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2'))
def test_macros(self):
- self.assertEqual(self.nrc.macros, {'macro1':['line1\n', 'line2\n'],
- 'macro2':['line3\n', 'line4\n']})
+ nrc = self.make_nrc("""\
+ macdef macro1
+ line1
+ line2
- def test_parses_passwords_with_hash_character(self):
- self.assertEqual(self.nrc.hosts['bar'], ('log1', 'acct1', 'pass#'))
+ macdef macro2
+ line3
+ line4
+ """)
+ self.assertEqual(nrc.macros, {'macro1': ['line1\n', 'line2\n'],
+ 'macro2': ['line3\n', 'line4\n']})
+
+ def _test_passwords(self, nrc, passwd):
+ nrc = self.make_nrc(nrc)
+ self.assertEqual(nrc.hosts['host.domain.com'], ('log', 'acct', passwd))
+
+ def test_password_with_leading_hash(self):
+ self._test_passwords("""\
+ machine host.domain.com login log password #pass account acct
+ """, '#pass')
+
+ def test_password_with_trailing_hash(self):
+ self._test_passwords("""\
+ machine host.domain.com login log password pass# account acct
+ """, 'pass#')
+
+ def test_password_with_internal_hash(self):
+ self._test_passwords("""\
+ machine host.domain.com login log password pa#ss account acct
+ """, 'pa#ss')
+
+ def _test_comment(self, nrc, passwd='pass'):
+ nrc = self.make_nrc(nrc)
+ self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, passwd))
+ self.assertEqual(nrc.hosts['bar.domain.com'], ('foo', None, 'pass'))
+
+ def test_comment_before_machine_line(self):
+ self._test_comment("""\
+ # comment
+ machine foo.domain.com login bar password pass
+ machine bar.domain.com login foo password pass
+ """)
+
+ def test_comment_before_machine_line_no_space(self):
+ self._test_comment("""\
+ #comment
+ machine foo.domain.com login bar password pass
+ machine bar.domain.com login foo password pass
+ """)
+
+ def test_comment_before_machine_line_hash_only(self):
+ self._test_comment("""\
+ #
+ machine foo.domain.com login bar password pass
+ machine bar.domain.com login foo password pass
+ """)
+
+ def test_comment_at_end_of_machine_line(self):
+ self._test_comment("""\
+ machine foo.domain.com login bar password pass # comment
+ machine bar.domain.com login foo password pass
+ """)
+
+ def test_comment_at_end_of_machine_line_no_space(self):
+ self._test_comment("""\
+ machine foo.domain.com login bar password pass #comment
+ machine bar.domain.com login foo password pass
+ """)
+
+ def test_comment_at_end_of_machine_line_pass_has_hash(self):
+ self._test_comment("""\
+ machine foo.domain.com login bar password #pass #comment
+ machine bar.domain.com login foo password pass
+ """, '#pass')
+
def test_main():
test_support.run_unittest(NetrcTestCase)
diff --git a/Lib/test/test_pkgutil.py b/Lib/test/test_pkgutil.py
index b3fc5d8..f665e96 100644
--- a/Lib/test/test_pkgutil.py
+++ b/Lib/test/test_pkgutil.py
@@ -15,11 +15,11 @@
def setUp(self):
self.dirname = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.dirname)
sys.path.insert(0, self.dirname)
def tearDown(self):
del sys.path[0]
- shutil.rmtree(self.dirname)
def test_getdata_filesys(self):
pkg = 'test_getdata_filesys'
@@ -78,6 +78,17 @@
del sys.modules[pkg]
+ def test_unreadable_dir_on_syspath(self):
+ # issue7367 - walk_packages failed if unreadable dir on sys.path
+ package_name = "unreadable_package"
+ d = os.path.join(self.dirname, package_name)
+ # this does not appear to create an unreadable dir on Windows
+ # but the test should not fail anyway
+ os.mkdir(d, 0)
+ self.addCleanup(os.rmdir, d)
+ for t in pkgutil.walk_packages(path=[self.dirname]):
+ self.fail("unexpected package found")
+
class PkgutilPEP302Tests(unittest.TestCase):
class MyTestLoader(object):
diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py
index 1ae5888..941d428 100644
--- a/Lib/test/test_platform.py
+++ b/Lib/test/test_platform.py
@@ -191,7 +191,7 @@
self.assertEqual(res[1], ('', '', ''))
if sys.byteorder == 'little':
- self.assertEqual(res[2], 'i386')
+ self.assertIn(res[2], ('i386', 'x86_64'))
else:
self.assertEqual(res[2], 'PowerPC')
diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py
index a5db21e..a6a7306 100644
--- a/Lib/test/test_posix.py
+++ b/Lib/test/test_posix.py
@@ -11,10 +11,14 @@
import os
import pwd
import shutil
+import stat
import sys
+import tempfile
import unittest
import warnings
+_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
+ test_support.TESTFN + '-dummy-symlink')
warnings.filterwarnings('ignore', '.* potential security risk .*',
RuntimeWarning)
@@ -25,9 +29,11 @@
# create empty file
fp = open(test_support.TESTFN, 'w+')
fp.close()
+ self.teardown_files = [ test_support.TESTFN ]
def tearDown(self):
- os.unlink(test_support.TESTFN)
+ for teardown_file in self.teardown_files:
+ os.unlink(teardown_file)
def testNoArgFunctions(self):
# test posix functions which take no arguments and have
@@ -258,7 +264,7 @@
def test_lchown(self):
os.unlink(test_support.TESTFN)
# create a symlink
- os.symlink('/tmp/dummy-symlink-target', test_support.TESTFN)
+ os.symlink(_DUMMY_SYMLINK, test_support.TESTFN)
self._test_all_chown_common(posix.lchown, test_support.TESTFN)
def test_chdir(self):
@@ -315,17 +321,49 @@
posix.utime(test_support.TESTFN, (int(now), int(now)))
posix.utime(test_support.TESTFN, (now, now))
- def test_chflags(self):
- if hasattr(posix, 'chflags'):
- st = os.stat(test_support.TESTFN)
- if hasattr(st, 'st_flags'):
- posix.chflags(test_support.TESTFN, st.st_flags)
+ def _test_chflags_regular_file(self, chflags_func, target_file):
+ st = os.stat(target_file)
+ self.assertTrue(hasattr(st, 'st_flags'))
+ chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE)
+ try:
+ new_st = os.stat(target_file)
+ self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
+ try:
+ fd = open(target_file, 'w+')
+ except IOError as e:
+ self.assertEqual(e.errno, errno.EPERM)
+ finally:
+ posix.chflags(target_file, st.st_flags)
- def test_lchflags(self):
- if hasattr(posix, 'lchflags'):
- st = os.stat(test_support.TESTFN)
- if hasattr(st, 'st_flags'):
- posix.lchflags(test_support.TESTFN, st.st_flags)
+ @unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
+ def test_chflags(self):
+ self._test_chflags_regular_file(posix.chflags, test_support.TESTFN)
+
+ @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
+ def test_lchflags_regular_file(self):
+ self._test_chflags_regular_file(posix.lchflags, test_support.TESTFN)
+
+ @unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
+ def test_lchflags_symlink(self):
+ testfn_st = os.stat(test_support.TESTFN)
+
+ self.assertTrue(hasattr(testfn_st, 'st_flags'))
+
+ os.symlink(test_support.TESTFN, _DUMMY_SYMLINK)
+ self.teardown_files.append(_DUMMY_SYMLINK)
+ dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
+
+ posix.lchflags(_DUMMY_SYMLINK,
+ dummy_symlink_st.st_flags | stat.UF_IMMUTABLE)
+ try:
+ new_testfn_st = os.stat(test_support.TESTFN)
+ new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
+
+ self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
+ self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
+ new_dummy_symlink_st.st_flags)
+ finally:
+ posix.lchflags(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
def test_getcwd_long_pathnames(self):
if hasattr(posix, 'getcwd'):
diff --git a/Lib/test/test_pydoc.py b/Lib/test/test_pydoc.py
index 2e67290..b433850 100644
--- a/Lib/test/test_pydoc.py
+++ b/Lib/test/test_pydoc.py
@@ -1,18 +1,18 @@
-import sys
import os
-import os.path
+import sys
import difflib
-import subprocess
+import __builtin__
import re
import pydoc
import inspect
+import keyword
import unittest
import xml.etree
import test.test_support
-from contextlib import contextmanager
from collections import namedtuple
+from test.script_helper import assert_python_ok
from test.test_support import (
- TESTFN, forget, rmtree, EnvironmentVarGuard, reap_children, captured_stdout)
+ TESTFN, rmtree, reap_children, captured_stdout)
from test import pydoc_mod
@@ -175,17 +175,15 @@
# output pattern for module with bad imports
badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
-def run_pydoc(module_name, *args):
+def run_pydoc(module_name, *args, **env):
"""
Runs pydoc on the specified module. Returns the stripped
output of pydoc.
"""
- cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
- try:
- output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
- return output.strip()
- finally:
- reap_children()
+ args = args + (module_name,)
+ # do not write bytecode files to avoid caching errors
+ rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
+ return out.strip()
def get_pydoc_html(module):
"Returns pydoc generated output as html"
@@ -258,42 +256,6 @@
self.assertEqual(expected, result,
"documentation for missing module found")
- def test_badimport(self):
- # This tests the fix for issue 5230, where if pydoc found the module
- # but the module had an internal import error pydoc would report no doc
- # found.
- modname = 'testmod_xyzzy'
- testpairs = (
- ('i_am_not_here', 'i_am_not_here'),
- ('test.i_am_not_here_either', 'i_am_not_here_either'),
- ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
- ('i_am_not_here.{}'.format(modname), 'i_am_not_here.{}'.format(modname)),
- ('test.{}'.format(modname), modname),
- )
-
- @contextmanager
- def newdirinpath(dir):
- os.mkdir(dir)
- sys.path.insert(0, dir)
- yield
- sys.path.pop(0)
- rmtree(dir)
-
- with newdirinpath(TESTFN), EnvironmentVarGuard() as env:
- env['PYTHONPATH'] = TESTFN
- fullmodname = os.path.join(TESTFN, modname)
- sourcefn = fullmodname + os.extsep + "py"
- for importstring, expectedinmsg in testpairs:
- f = open(sourcefn, 'w')
- f.write("import {}\n".format(importstring))
- f.close()
- try:
- result = run_pydoc(modname)
- finally:
- forget(modname)
- expected = badimport_pattern % (modname, expectedinmsg)
- self.assertEqual(expected, result)
-
def test_input_strip(self):
missing_module = " test.i_am_not_here "
result = run_pydoc(missing_module)
@@ -316,6 +278,55 @@
"<type 'exceptions.Exception'>")
+class PydocImportTest(unittest.TestCase):
+
+ def setUp(self):
+ self.test_dir = os.mkdir(TESTFN)
+ self.addCleanup(rmtree, TESTFN)
+
+ def test_badimport(self):
+ # This tests the fix for issue 5230, where if pydoc found the module
+ # but the module had an internal import error pydoc would report no doc
+ # found.
+ modname = 'testmod_xyzzy'
+ testpairs = (
+ ('i_am_not_here', 'i_am_not_here'),
+ ('test.i_am_not_here_either', 'i_am_not_here_either'),
+ ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
+ ('i_am_not_here.{}'.format(modname),
+ 'i_am_not_here.{}'.format(modname)),
+ ('test.{}'.format(modname), modname),
+ )
+
+ sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
+ for importstring, expectedinmsg in testpairs:
+ with open(sourcefn, 'w') as f:
+ f.write("import {}\n".format(importstring))
+ result = run_pydoc(modname, PYTHONPATH=TESTFN)
+ expected = badimport_pattern % (modname, expectedinmsg)
+ self.assertEqual(expected, result)
+
+ def test_apropos_with_bad_package(self):
+ # Issue 7425 - pydoc -k failed when bad package on path
+ pkgdir = os.path.join(TESTFN, "syntaxerr")
+ os.mkdir(pkgdir)
+ badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
+ with open(badsyntax, 'w') as f:
+ f.write("invalid python syntax = $1\n")
+ result = run_pydoc('nothing', '-k', PYTHONPATH=TESTFN)
+ self.assertEqual('', result)
+
+ def test_apropos_with_unreadable_dir(self):
+ # Issue 7367 - pydoc -k failed when unreadable dir on path
+ self.unreadable_dir = os.path.join(TESTFN, "unreadable")
+ os.mkdir(self.unreadable_dir, 0)
+ self.addCleanup(os.rmdir, self.unreadable_dir)
+ # Note, on Windows the directory appears to be still
+ # readable so this is not really testing the issue there
+ result = run_pydoc('nothing', '-k', PYTHONPATH=TESTFN)
+ self.assertEqual('', result)
+
+
class TestDescriptions(unittest.TestCase):
def test_module(self):
@@ -351,9 +362,37 @@
self.assertIn('_asdict', helptext)
+class TestHelper(unittest.TestCase):
+ def test_keywords(self):
+ self.assertEqual(sorted(pydoc.Helper.keywords),
+ sorted(keyword.kwlist))
+
+ def test_builtin(self):
+ for name in ('str', 'str.translate', '__builtin__.str',
+ '__builtin__.str.translate'):
+ # test low-level function
+ self.assertIsNotNone(pydoc.locate(name))
+ # test high-level function
+ try:
+ pydoc.render_doc(name)
+ except ImportError:
+ self.fail('finding the doc of {!r} failed'.format(o))
+
+ for name in ('not__builtin__', 'strrr', 'strr.translate',
+ 'str.trrrranslate', '__builtin__.strrr',
+ '__builtin__.str.trrranslate'):
+ self.assertIsNone(pydoc.locate(name))
+ self.assertRaises(ImportError, pydoc.render_doc, name)
+
+
def test_main():
- test.test_support.run_unittest(PyDocDocTest,
- TestDescriptions)
+ try:
+ test.test_support.run_unittest(PyDocDocTest,
+ PydocImportTest,
+ TestDescriptions,
+ TestHelper)
+ finally:
+ reap_children()
if __name__ == "__main__":
test_main()
diff --git a/Lib/test/test_robotparser.py b/Lib/test/test_robotparser.py
index 3376a8a..b3d4a46 100644
--- a/Lib/test/test_robotparser.py
+++ b/Lib/test/test_robotparser.py
@@ -1,5 +1,6 @@
import unittest, StringIO, robotparser
from test import test_support
+from urllib2 import urlopen, HTTPError
class RobotTestCase(unittest.TestCase):
def __init__(self, index, parser, url, good, agent):
@@ -234,13 +235,27 @@
test_support.requires('network')
with test_support.transient_internet('mueblesmoraleda.com'):
url = 'http://mueblesmoraleda.com'
+ robots_url = url + "/robots.txt"
+ # First check the URL is usable for our purposes, since the
+ # test site is a bit flaky.
+ try:
+ urlopen(robots_url)
+ except HTTPError as e:
+ if e.code not in {401, 403}:
+ self.skipTest(
+ "%r should return a 401 or 403 HTTP error, not %r"
+ % (robots_url, e.code))
+ else:
+ self.skipTest(
+ "%r should return a 401 or 403 HTTP error, not succeed"
+ % (robots_url))
parser = robotparser.RobotFileParser()
parser.set_url(url)
try:
parser.read()
except IOError:
self.skipTest('%s is unavailable' % url)
- self.assertEqual(parser.can_fetch("*", url+"/robots.txt"), False)
+ self.assertEqual(parser.can_fetch("*", robots_url), False)
def testPythonOrg(self):
test_support.requires('network')
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
index fdc0bc1..b4e5415 100644
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -349,6 +349,8 @@
self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
tmpdir2 = self.mkdtemp()
+ # force shutil to create the directory
+ os.rmdir(tmpdir2)
unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
"source and target should be on same drive")
@@ -464,6 +466,8 @@
self.write_file([tmpdir, 'file2'], 'xxx')
tmpdir2 = self.mkdtemp()
+ # force shutil to create the directory
+ os.rmdir(tmpdir2)
base_name = os.path.join(tmpdir2, 'archive')
_make_zipfile(base_name, tmpdir)
@@ -805,6 +809,24 @@
self.assertTrue(srcfile._exited_with[0] is None)
self.assertTrue(srcfile._raised)
+ def test_move_dir_caseinsensitive(self):
+ # Renames a folder to the same name
+ # but a different case.
+
+ self.src_dir = tempfile.mkdtemp()
+ dst_dir = os.path.join(
+ os.path.dirname(self.src_dir),
+ os.path.basename(self.src_dir).upper())
+ self.assertNotEqual(self.src_dir, dst_dir)
+
+ try:
+ shutil.move(self.src_dir, dst_dir)
+ self.assertTrue(os.path.isdir(dst_dir))
+ finally:
+ if os.path.exists(dst_dir):
+ os.rmdir(dst_dir)
+
+
def test_main():
test_support.run_unittest(TestShutil, TestMove, TestCopyFile)
diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py
index 42a10be..81806c9 100644
--- a/Lib/test/test_smtplib.py
+++ b/Lib/test/test_smtplib.py
@@ -330,15 +330,14 @@
self.push(resp)
def smtp_VRFY(self, arg):
- raw_addr = email.utils.parseaddr(arg)[1]
- quoted_addr = smtplib.quoteaddr(arg)
- if raw_addr in sim_users:
- self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
+ # For max compatibility smtplib should be sending the raw address.
+ if arg in sim_users:
+ self.push('250 %s %s' % (sim_users[arg], smtplib.quoteaddr(arg)))
else:
self.push('550 No such user: %s' % arg)
def smtp_EXPN(self, arg):
- list_name = email.utils.parseaddr(arg)[1].lower()
+ list_name = arg.lower()
if list_name in sim_lists:
user_list = sim_lists[list_name]
for n, user_email in enumerate(user_list):
@@ -454,7 +453,7 @@
self.assertEqual(smtp.vrfy(email), expected_known)
u = 'nobody@nowhere.com'
- expected_unknown = (550, 'No such user: %s' % smtplib.quoteaddr(u))
+ expected_unknown = (550, 'No such user: %s' % u)
self.assertEqual(smtp.vrfy(u), expected_unknown)
smtp.quit()
diff --git a/Lib/test/test_smtpnet.py b/Lib/test/test_smtpnet.py
index f25343d..2dc39eb 100644
--- a/Lib/test/test_smtpnet.py
+++ b/Lib/test/test_smtpnet.py
@@ -17,6 +17,13 @@
server.ehlo()
server.quit()
+ def test_connect_default_port(self):
+ test_support.get_attribute(smtplib, 'SMTP_SSL')
+ with test_support.transient_internet(self.testServer):
+ server = smtplib.SMTP_SSL(self.testServer)
+ server.ehlo()
+ server.quit()
+
def test_main():
test_support.run_unittest(SmtpSSLTest)
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
index d41bca5..0d6240d 100644
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -145,8 +145,8 @@
def clientRun(self, test_func):
self.server_ready.wait()
- self.client_ready.set()
self.clientSetUp()
+ self.client_ready.set()
with test_support.check_py3k_warnings():
if not callable(test_func):
raise TypeError("test_func must be a callable function.")
@@ -274,6 +274,45 @@
self.assertRaises(socket.error, raise_gaierror,
"Error raising socket exception.")
+ def testSendtoErrors(self):
+ # Testing that sendto doens't masks failures. See #10169.
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.addCleanup(s.close)
+ s.bind(('', 0))
+ sockname = s.getsockname()
+ # 2 args
+ with self.assertRaises(UnicodeEncodeError):
+ s.sendto(u'\u2620', sockname)
+ with self.assertRaises(TypeError) as cm:
+ s.sendto(5j, sockname)
+ self.assertIn('not complex', str(cm.exception))
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo', None)
+ self.assertIn('not NoneType', str(cm.exception))
+ # 3 args
+ with self.assertRaises(UnicodeEncodeError):
+ s.sendto(u'\u2620', 0, sockname)
+ with self.assertRaises(TypeError) as cm:
+ s.sendto(5j, 0, sockname)
+ self.assertIn('not complex', str(cm.exception))
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo', 0, None)
+ self.assertIn('not NoneType', str(cm.exception))
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo', 'bar', sockname)
+ self.assertIn('an integer is required', str(cm.exception))
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo', None, None)
+ self.assertIn('an integer is required', str(cm.exception))
+ # wrong number of args
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo')
+ self.assertIn('(1 given)', str(cm.exception))
+ with self.assertRaises(TypeError) as cm:
+ s.sendto('foo', 0, sockname, 4)
+ self.assertIn('(4 given)', str(cm.exception))
+
+
def testCrucialConstants(self):
# Testing for mission critical constants
socket.AF_INET
@@ -661,6 +700,13 @@
def test_sendall_interrupted_with_timeout(self):
self.check_sendall_interrupted(True)
+ def testListenBacklog0(self):
+ srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ srv.bind((HOST, 0))
+ # backlog = 0
+ srv.listen(0)
+ srv.close()
+
@unittest.skipUnless(thread, 'Threading required for this test.')
class BasicTCPTest(SocketConnectedTest):
diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py
index 4825a4a..41634e7 100644
--- a/Lib/test/test_socketserver.py
+++ b/Lib/test/test_socketserver.py
@@ -66,7 +66,7 @@
"""Test all socket servers."""
def setUp(self):
- signal_alarm(20) # Kill deadlocks after 20 seconds.
+ signal_alarm(60) # Kill deadlocks after 60 seconds.
self.port_seed = 0
self.test_files = []
@@ -281,4 +281,3 @@
if __name__ == "__main__":
test_main()
- signal_alarm(3) # Shutdown shouldn't take more than 3 seconds.
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
index 2567218..aa6c850 100644
--- a/Lib/test/test_ssl.py
+++ b/Lib/test/test_ssl.py
@@ -20,12 +20,7 @@
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
-# Optionally test SSL support, if we have it in the tested platform
-skip_expected = False
-try:
- import ssl
-except ImportError:
- skip_expected = True
+ssl = test_support.import_module("ssl")
HOST = test_support.HOST
CERTFILE = None
@@ -58,32 +53,35 @@
# Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2
def skip_if_broken_ubuntu_ssl(func):
- # We need to access the lower-level wrapper in order to create an
- # implicit SSL context without trying to connect or listen.
- try:
- import _ssl
- except ImportError:
- # The returned function won't get executed, just ignore the error
- pass
- @functools.wraps(func)
- def f(*args, **kwargs):
+ if hasattr(ssl, 'PROTOCOL_SSLv2'):
+ # We need to access the lower-level wrapper in order to create an
+ # implicit SSL context without trying to connect or listen.
try:
- s = socket.socket(socket.AF_INET)
- _ssl.sslwrap(s._sock, 0, None, None,
- ssl.CERT_NONE, ssl.PROTOCOL_SSLv2, None, None)
- except ssl.SSLError as e:
- if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
- platform.linux_distribution() == ('debian', 'squeeze/sid', '')
- and 'Invalid SSL protocol variant specified' in str(e)):
- raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
- return func(*args, **kwargs)
- return f
+ import _ssl
+ except ImportError:
+ # The returned function won't get executed, just ignore the error
+ pass
+ @functools.wraps(func)
+ def f(*args, **kwargs):
+ try:
+ s = socket.socket(socket.AF_INET)
+ _ssl.sslwrap(s._sock, 0, None, None,
+ ssl.CERT_NONE, ssl.PROTOCOL_SSLv2, None, None)
+ except ssl.SSLError as e:
+ if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
+ platform.linux_distribution() == ('debian', 'squeeze/sid', '')
+ and 'Invalid SSL protocol variant specified' in str(e)):
+ raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
+ return func(*args, **kwargs)
+ return f
+ else:
+ return func
class BasicSocketTests(unittest.TestCase):
def test_constants(self):
- ssl.PROTOCOL_SSLv2
+ #ssl.PROTOCOL_SSLv2
ssl.PROTOCOL_SSLv23
ssl.PROTOCOL_SSLv3
ssl.PROTOCOL_TLSv1
@@ -112,6 +110,23 @@
p = ssl._ssl._test_decode_cert(CERTFILE, False)
if test_support.verbose:
sys.stdout.write("\n" + pprint.pformat(p) + "\n")
+ self.assertEqual(p['subject'],
+ ((('countryName', u'US'),),
+ (('stateOrProvinceName', u'Delaware'),),
+ (('localityName', u'Wilmington'),),
+ (('organizationName', u'Python Software Foundation'),),
+ (('organizationalUnitName', u'SSL'),),
+ (('commonName', u'somemachine.python.org'),)),
+ )
+ # Issue #13034: the subjectAltName in some certificates
+ # (notably projects.developer.nokia.com:443) wasn't parsed
+ p = ssl._ssl._test_decode_cert(NOKIACERT)
+ if test_support.verbose:
+ sys.stdout.write("\n" + pprint.pformat(p) + "\n")
+ self.assertEqual(p['subjectAltName'],
+ (('DNS', 'projects.developer.nokia.com'),
+ ('DNS', 'projects.forum.nokia.com'))
+ )
def test_DER_to_PEM(self):
with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
@@ -1008,7 +1023,8 @@
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED)
- try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
+ if hasattr(ssl, 'PROTOCOL_SSLv2'):
+ try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False)
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
@@ -1020,7 +1036,8 @@
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED)
- try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
+ if hasattr(ssl, 'PROTOCOL_SSLv2'):
+ try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False)
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False)
@@ -1329,18 +1346,18 @@
def test_main(verbose=False):
- if skip_expected:
- raise unittest.SkipTest("No SSL support")
-
- global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT
+ global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT
CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
"keycert.pem")
SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
os.path.dirname(__file__) or os.curdir,
"https_svn_python_org_root.pem")
+ NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir,
+ "nokia.pem")
if (not os.path.exists(CERTFILE) or
- not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)):
+ not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or
+ not os.path.exists(NOKIACERT)):
raise test_support.TestFailed("Can't read certificate files!")
tests = [BasicTests, BasicSocketTests]
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
index b635ef3..1aa2c0a 100644
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -113,6 +113,16 @@
env=newenv)
self.assertEqual(rc, 1)
+ def test_invalid_args(self):
+ # Popen() called with invalid arguments should raise TypeError
+ # but Popen.__del__ should not complain (issue #12085)
+ with test_support.captured_stderr() as s:
+ self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
+ argcount = subprocess.Popen.__init__.__code__.co_argcount
+ too_many_args = [0] * (argcount + 1)
+ self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
+ self.assertEqual(s.getvalue(), '')
+
def test_stdin_none(self):
# .stdin is None when not redirected
p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
@@ -654,6 +664,24 @@
except (ImportError, ValueError, resource.error):
pass
+ @unittest.skipUnless(hasattr(signal, 'SIGALRM'),
+ "Requires signal.SIGALRM")
+ def test_communicate_eintr(self):
+ # Issue #12493: communicate() should handle EINTR
+ def handler(signum, frame):
+ pass
+ old_handler = signal.signal(signal.SIGALRM, handler)
+ self.addCleanup(signal.signal, signal.SIGALRM, old_handler)
+
+ # the process is running for 2 seconds
+ args = [sys.executable, "-c", 'import time; time.sleep(2)']
+ for stream in ('stdout', 'stderr'):
+ kw = {stream: subprocess.PIPE}
+ with subprocess.Popen(args, **kw) as process:
+ signal.alarm(1)
+ # communicate() will be interrupted by SIGALRM
+ process.communicate()
+
@unittest.skipIf(mswindows, "POSIX specific tests")
class POSIXProcessTestCase(BaseTestCase):
@@ -849,6 +877,64 @@
# all standard fds closed.
self.check_close_std_fds([0, 1, 2])
+ def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
+ # open up some temporary files
+ temps = [mkstemp() for i in range(3)]
+ temp_fds = [fd for fd, fname in temps]
+ try:
+ # unlink the files -- we won't need to reopen them
+ for fd, fname in temps:
+ os.unlink(fname)
+
+ # save a copy of the standard file descriptors
+ saved_fds = [os.dup(fd) for fd in range(3)]
+ try:
+ # duplicate the temp files over the standard fd's 0, 1, 2
+ for fd, temp_fd in enumerate(temp_fds):
+ os.dup2(temp_fd, fd)
+
+ # write some data to what will become stdin, and rewind
+ os.write(stdin_no, b"STDIN")
+ os.lseek(stdin_no, 0, 0)
+
+ # now use those files in the given order, so that subprocess
+ # has to rearrange them in the child
+ p = subprocess.Popen([sys.executable, "-c",
+ 'import sys; got = sys.stdin.read();'
+ 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
+ stdin=stdin_no,
+ stdout=stdout_no,
+ stderr=stderr_no)
+ p.wait()
+
+ for fd in temp_fds:
+ os.lseek(fd, 0, 0)
+
+ out = os.read(stdout_no, 1024)
+ err = test_support.strip_python_stderr(os.read(stderr_no, 1024))
+ finally:
+ for std, saved in enumerate(saved_fds):
+ os.dup2(saved, std)
+ os.close(saved)
+
+ self.assertEqual(out, b"got STDIN")
+ self.assertEqual(err, b"err")
+
+ finally:
+ for fd in temp_fds:
+ os.close(fd)
+
+ # When duping fds, if there arises a situation where one of the fds is
+ # either 0, 1 or 2, it is possible that it is overwritten (#12607).
+ # This tests all combinations of this.
+ def test_swap_fds(self):
+ self.check_swap_fds(0, 1, 2)
+ self.check_swap_fds(0, 2, 1)
+ self.check_swap_fds(1, 0, 2)
+ self.check_swap_fds(1, 2, 0)
+ self.check_swap_fds(2, 0, 1)
+ self.check_swap_fds(2, 1, 0)
+
def test_wait_when_sigchild_ignored(self):
# NOTE: sigchild_ignore.py may not be an effective test on all OSes.
sigchild_ignore = test_support.findfile("sigchild_ignore.py",
@@ -859,6 +945,87 @@
self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
" non-zero with this error:\n%s" % stderr)
+ def test_zombie_fast_process_del(self):
+ # Issue #12650: on Unix, if Popen.__del__() was called before the
+ # process exited, it wouldn't be added to subprocess._active, and would
+ # remain a zombie.
+ # spawn a Popen, and delete its reference before it exits
+ p = subprocess.Popen([sys.executable, "-c",
+ 'import sys, time;'
+ 'time.sleep(0.2)'],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ self.addCleanup(p.stdout.close)
+ self.addCleanup(p.stderr.close)
+ ident = id(p)
+ pid = p.pid
+ del p
+ # check that p is in the active processes list
+ self.assertIn(ident, [id(o) for o in subprocess._active])
+
+ def test_leak_fast_process_del_killed(self):
+ # Issue #12650: on Unix, if Popen.__del__() was called before the
+ # process exited, and the process got killed by a signal, it would never
+ # be removed from subprocess._active, which triggered a FD and memory
+ # leak.
+ # spawn a Popen, delete its reference and kill it
+ p = subprocess.Popen([sys.executable, "-c",
+ 'import time;'
+ 'time.sleep(3)'],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ self.addCleanup(p.stdout.close)
+ self.addCleanup(p.stderr.close)
+ ident = id(p)
+ pid = p.pid
+ del p
+ os.kill(pid, signal.SIGKILL)
+ # check that p is in the active processes list
+ self.assertIn(ident, [id(o) for o in subprocess._active])
+
+ # let some time for the process to exit, and create a new Popen: this
+ # should trigger the wait() of p
+ time.sleep(0.2)
+ with self.assertRaises(EnvironmentError) as c:
+ with subprocess.Popen(['nonexisting_i_hope'],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE) as proc:
+ pass
+ # p should have been wait()ed on, and removed from the _active list
+ self.assertRaises(OSError, os.waitpid, pid, 0)
+ self.assertNotIn(ident, [id(o) for o in subprocess._active])
+
+ def test_pipe_cloexec(self):
+ # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
+ # and are not inherited by another child process.
+ p1 = subprocess.Popen([sys.executable, "-c",
+ 'import os;'
+ 'os.read(0, 1)'
+ ],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ p2 = subprocess.Popen([sys.executable, "-c", """if True:
+ import os, errno, sys
+ for fd in %r:
+ try:
+ os.close(fd)
+ except OSError as e:
+ if e.errno != errno.EBADF:
+ raise
+ else:
+ sys.exit(1)
+ sys.exit(0)
+ """ % [f.fileno() for f in (p1.stdin, p1.stdout,
+ p1.stderr)]
+ ],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, close_fds=False)
+ p1.communicate('foo')
+ _, stderr = p2.communicate()
+
+ self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
+
@unittest.skipUnless(mswindows, "Windows specific tests")
class Win32ProcessTestCase(BaseTestCase):
@@ -994,7 +1161,6 @@
subprocess._eintr_retry_call(fake_os_func, 666))
self.assertEqual([(256, 999), (666,), (666,)], record_calls)
-
@unittest.skipUnless(mswindows, "mswindows only")
class CommandsWithSpaces (BaseTestCase):
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index cb2e03b..4cdfe7f 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -35,7 +35,8 @@
"run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
"BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
"threading_cleanup", "reap_children", "cpython_only",
- "check_impl_detail", "get_attribute", "py3k_bytes"]
+ "check_impl_detail", "get_attribute", "py3k_bytes",
+ "import_fresh_module"]
class Error(Exception):
@@ -83,23 +84,20 @@
def _save_and_remove_module(name, orig_modules):
"""Helper function to save and remove a module from sys.modules
- Return value is True if the module was in sys.modules and
- False otherwise."""
- saved = True
- try:
- orig_modules[name] = sys.modules[name]
- except KeyError:
- saved = False
- else:
+ Raise ImportError if the module can't be imported."""
+ # try to import the module and raise an error if it can't be imported
+ if name not in sys.modules:
+ __import__(name)
del sys.modules[name]
- return saved
-
+ for modname in list(sys.modules):
+ if modname == name or modname.startswith(name + '.'):
+ orig_modules[modname] = sys.modules[modname]
+ del sys.modules[modname]
def _save_and_block_module(name, orig_modules):
"""Helper function to save and block a module in sys.modules
- Return value is True if the module was in sys.modules and
- False otherwise."""
+ Return True if the module was in sys.modules, False otherwise."""
saved = True
try:
orig_modules[name] = sys.modules[name]
@@ -115,14 +113,15 @@
the sys.modules cache is restored to its original state.
Modules named in fresh are also imported anew if needed by the import.
+ If one of these modules can't be imported, None is returned.
Importing of modules named in blocked is prevented while the fresh import
takes place.
If deprecated is True, any module or package deprecation messages
will be suppressed."""
- # NOTE: test_heapq and test_warnings include extra sanity checks to make
- # sure that this utility function is working as expected
+ # NOTE: test_heapq, test_json, and test_warnings include extra sanity
+ # checks to make sure that this utility function is working as expected
with _ignore_deprecated_imports(deprecated):
# Keep track of modules saved for later restoration as well
# as those which just need a blocking entry removed
@@ -136,6 +135,8 @@
if not _save_and_block_module(blocked_name, orig_modules):
names_to_remove.append(blocked_name)
fresh_module = importlib.import_module(name)
+ except ImportError:
+ fresh_module = None
finally:
for orig_name, module in orig_modules.items():
sys.modules[orig_name] = module
@@ -762,6 +763,7 @@
('ETIMEDOUT', 110),
]
default_gai_errnos = [
+ ('EAI_AGAIN', -3),
('EAI_NONAME', -2),
('EAI_NODATA', -5),
]
@@ -813,14 +815,8 @@
@contextlib.contextmanager
def captured_output(stream_name):
- """Run the 'with' statement body using a StringIO object in place of a
- specific attribute on the sys module.
- Example use (with 'stream_name=stdout')::
-
- with captured_stdout() as s:
- print "hello"
- assert s.getvalue() == "hello"
- """
+ """Return a context manager used by captured_stdout and captured_stdin
+ that temporarily replaces the sys stream *stream_name* with a StringIO."""
import StringIO
orig_stdout = getattr(sys, stream_name)
setattr(sys, stream_name, StringIO.StringIO())
@@ -830,8 +826,17 @@
setattr(sys, stream_name, orig_stdout)
def captured_stdout():
+ """Capture the output of sys.stdout:
+
+ with captured_stdout() as s:
+ print "hello"
+ self.assertEqual(s.getvalue(), "hello")
+ """
return captured_output("stdout")
+def captured_stderr():
+ return captured_output("stderr")
+
def captured_stdin():
return captured_output("stdin")
diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py
index df8c56f..1f77f9b 100644
--- a/Lib/test/test_sys_settrace.py
+++ b/Lib/test/test_sys_settrace.py
@@ -282,11 +282,11 @@
self.compare_events(func.func_code.co_firstlineno,
tracer.events, func.events)
- def set_and_retrieve_none(self):
+ def test_set_and_retrieve_none(self):
sys.settrace(None)
assert sys.gettrace() is None
- def set_and_retrieve_func(self):
+ def test_set_and_retrieve_func(self):
def fn(*args):
pass
diff --git a/Lib/test/test_sysconfig.py b/Lib/test/test_sysconfig.py
index 142eb2f..716fa5e 100644
--- a/Lib/test/test_sysconfig.py
+++ b/Lib/test/test_sysconfig.py
@@ -1,9 +1,5 @@
-"""Tests for 'site'.
+"""Tests for sysconfig."""
-Tests assume the initial paths in sys.path once the interpreter has begun
-executing have not been removed.
-
-"""
import unittest
import sys
import os
@@ -141,7 +137,7 @@
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
- os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
+ get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
@@ -161,7 +157,6 @@
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
- os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
@@ -176,7 +171,7 @@
sys.maxint = maxint
# macbook with fat binaries (fat, universal or fat64)
- os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
+ get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
@@ -256,14 +251,66 @@
unlink(link)
def test_user_similar(self):
- # Issue 8759 : make sure the posix scheme for the users
+ # Issue #8759: make sure the posix scheme for the users
# is similar to the global posix_prefix one
base = get_config_var('base')
user = get_config_var('userbase')
+ # the global scheme mirrors the distinction between prefix and
+ # exec-prefix but not the user scheme, so we have to adapt the paths
+ # before comparing (issue #9100)
+ adapt = sys.prefix != sys.exec_prefix
for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
global_path = get_path(name, 'posix_prefix')
+ if adapt:
+ global_path = global_path.replace(sys.exec_prefix, sys.prefix)
+ base = base.replace(sys.exec_prefix, sys.prefix)
user_path = get_path(name, 'posix_user')
- self.assertEqual(user_path, global_path.replace(base, user))
+ self.assertEqual(user_path, global_path.replace(base, user, 1))
+
+ @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
+ def test_platform_in_subprocess(self):
+ my_platform = sysconfig.get_platform()
+
+ # Test without MACOSX_DEPLOYMENT_TARGET in the environment
+
+ env = os.environ.copy()
+ if 'MACOSX_DEPLOYMENT_TARGET' in env:
+ del env['MACOSX_DEPLOYMENT_TARGET']
+
+ with open('/dev/null', 'w') as devnull_fp:
+ p = subprocess.Popen([
+ sys.executable, '-c',
+ 'import sysconfig; print(sysconfig.get_platform())',
+ ],
+ stdout=subprocess.PIPE,
+ stderr=devnull_fp,
+ env=env)
+ test_platform = p.communicate()[0].strip()
+ test_platform = test_platform.decode('utf-8')
+ status = p.wait()
+
+ self.assertEqual(status, 0)
+ self.assertEqual(my_platform, test_platform)
+
+
+ # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
+ # using a value that is unlikely to be the default one.
+ env = os.environ.copy()
+ env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
+
+ p = subprocess.Popen([
+ sys.executable, '-c',
+ 'import sysconfig; print(sysconfig.get_platform())',
+ ],
+ stdout=subprocess.PIPE,
+ stderr=open('/dev/null'),
+ env=env)
+ test_platform = p.communicate()[0].strip()
+ test_platform = test_platform.decode('utf-8')
+ status = p.wait()
+
+ self.assertEqual(status, 0)
+ self.assertEqual(my_platform, test_platform)
def test_main():
run_unittest(TestSysConfig)
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
index cda5262..6962f8e 100644
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -843,6 +843,94 @@
finally:
os.chdir(cwd)
+ @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
+ def test_extractall_symlinks(self):
+ # Test if extractall works properly when tarfile contains symlinks
+ tempdir = os.path.join(TEMPDIR, "testsymlinks")
+ temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
+ os.mkdir(tempdir)
+ try:
+ source_file = os.path.join(tempdir,'source')
+ target_file = os.path.join(tempdir,'symlink')
+ with open(source_file,'w') as f:
+ f.write('something\n')
+ os.symlink(source_file, target_file)
+ tar = tarfile.open(temparchive,'w')
+ tar.add(source_file, arcname=os.path.basename(source_file))
+ tar.add(target_file, arcname=os.path.basename(target_file))
+ tar.close()
+ # Let's extract it to the location which contains the symlink
+ tar = tarfile.open(temparchive,'r')
+ # this should not raise OSError: [Errno 17] File exists
+ try:
+ tar.extractall(path=tempdir)
+ except OSError:
+ self.fail("extractall failed with symlinked files")
+ finally:
+ tar.close()
+ finally:
+ os.unlink(temparchive)
+ shutil.rmtree(tempdir)
+
+ @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
+ def test_extractall_broken_symlinks(self):
+ # Test if extractall works properly when tarfile contains broken
+ # symlinks
+ tempdir = os.path.join(TEMPDIR, "testsymlinks")
+ temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
+ os.mkdir(tempdir)
+ try:
+ source_file = os.path.join(tempdir,'source')
+ target_file = os.path.join(tempdir,'symlink')
+ with open(source_file,'w') as f:
+ f.write('something\n')
+ os.symlink(source_file, target_file)
+ tar = tarfile.open(temparchive,'w')
+ tar.add(target_file, arcname=os.path.basename(target_file))
+ tar.close()
+ # remove the real file
+ os.unlink(source_file)
+ # Let's extract it to the location which contains the symlink
+ tar = tarfile.open(temparchive,'r')
+ # this should not raise OSError: [Errno 17] File exists
+ try:
+ tar.extractall(path=tempdir)
+ except OSError:
+ self.fail("extractall failed with broken symlinked files")
+ finally:
+ tar.close()
+ finally:
+ os.unlink(temparchive)
+ shutil.rmtree(tempdir)
+
+ @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
+ def test_extractall_hardlinks(self):
+ # Test if extractall works properly when tarfile contains symlinks
+ tempdir = os.path.join(TEMPDIR, "testsymlinks")
+ temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
+ os.mkdir(tempdir)
+ try:
+ source_file = os.path.join(tempdir,'source')
+ target_file = os.path.join(tempdir,'symlink')
+ with open(source_file,'w') as f:
+ f.write('something\n')
+ os.link(source_file, target_file)
+ tar = tarfile.open(temparchive,'w')
+ tar.add(source_file, arcname=os.path.basename(source_file))
+ tar.add(target_file, arcname=os.path.basename(target_file))
+ tar.close()
+ # Let's extract it to the location which contains the symlink
+ tar = tarfile.open(temparchive,'r')
+ # this should not raise OSError: [Errno 17] File exists
+ try:
+ tar.extractall(path=tempdir)
+ except OSError:
+ self.fail("extractall failed with linked files")
+ finally:
+ tar.close()
+ finally:
+ os.unlink(temparchive)
+ shutil.rmtree(tempdir)
class StreamWriteTest(WriteTestBase):
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index 0062634..bdb7f14 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -417,6 +417,13 @@
class ThreadJoinOnShutdown(BaseTestCase):
+ # Between fork() and exec(), only async-safe functions are allowed (issues
+ # #12316 and #11870), and fork() from a worker thread is known to trigger
+ # problems with some operating systems (issue #3863): skip problematic tests
+ # on platforms known to behave badly.
+ platforms_to_skip = ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
+ 'os2emx')
+
def _run_and_join(self, script):
script = """if 1:
import sys, os, time, threading
@@ -448,11 +455,10 @@
self._run_and_join(script)
+ @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+ @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_2_join_in_forked_process(self):
# Like the test above, but from a forked interpreter
- import os
- if not hasattr(os, 'fork'):
- return
script = """if 1:
childpid = os.fork()
if childpid != 0:
@@ -466,19 +472,11 @@
"""
self._run_and_join(script)
+ @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+ @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_3_join_in_forked_from_thread(self):
# Like the test above, but fork() was called from a worker thread
# In the forked process, the main Thread object must be marked as stopped.
- import os
- if not hasattr(os, 'fork'):
- return
- # Skip platforms with known problems forking from a worker thread.
- # See http://bugs.python.org/issue3863.
- if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'netbsd5',
- 'os2emx'):
- print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread'
- ' due to known OS bugs on'), sys.platform
- return
script = """if 1:
main_thread = threading.current_thread()
def worker():
@@ -507,15 +505,11 @@
self.assertEqual(data, expected_output)
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+ @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_4_joining_across_fork_in_worker_thread(self):
# There used to be a possible deadlock when forking from a child
# thread. See http://bugs.python.org/issue6643.
- # Skip platforms with known problems forking from a worker thread.
- # See http://bugs.python.org/issue3863.
- if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
- raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
-
# The script takes the following steps:
# - The main thread in the parent process starts a new thread and then
# tries to join it.
@@ -584,6 +578,7 @@
self.assertScriptHasOutput(script, "end of main\n")
@unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+ @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug")
def test_5_clear_waiter_locks_to_avoid_crash(self):
# Check that a spawned thread that forks doesn't segfault on certain
# platforms, namely OS X. This used to happen if there was a waiter
@@ -596,10 +591,6 @@
# lock will be acquired, we can't know if the internal mutex will be
# acquired at the time of the fork.
- # Skip platforms with known problems forking from a worker thread.
- # See http://bugs.python.org/issue3863.
- if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
- raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
script = """if True:
import os, time, threading
@@ -689,6 +680,37 @@
class BoundedSemaphoreTests(lock_tests.BoundedSemaphoreTests):
semtype = staticmethod(threading.BoundedSemaphore)
+ @unittest.skipUnless(sys.platform == 'darwin', 'test macosx problem')
+ def test_recursion_limit(self):
+ # Issue 9670
+ # test that excessive recursion within a non-main thread causes
+ # an exception rather than crashing the interpreter on platforms
+ # like Mac OS X or FreeBSD which have small default stack sizes
+ # for threads
+ script = """if True:
+ import threading
+
+ def recurse():
+ return recurse()
+
+ def outer():
+ try:
+ recurse()
+ except RuntimeError:
+ pass
+
+ w = threading.Thread(target=outer)
+ w.start()
+ w.join()
+ print('end of main thread')
+ """
+ expected_output = "end of main thread\n"
+ p = subprocess.Popen([sys.executable, "-c", script],
+ stdout=subprocess.PIPE)
+ stdout, stderr = p.communicate()
+ data = stdout.decode().replace('\r', '')
+ self.assertEqual(p.returncode, 0, "Unexpected error")
+ self.assertEqual(data, expected_output)
def test_main():
test.test_support.run_unittest(LockTests, RLockTests, EventTests,
diff --git a/Lib/test/test_tk.py b/Lib/test/test_tk.py
index 49ca53f..8625db2 100644
--- a/Lib/test/test_tk.py
+++ b/Lib/test/test_tk.py
@@ -1,18 +1,9 @@
import os
-import unittest
from test import test_support
# Skip test if _tkinter wasn't built.
test_support.import_module('_tkinter')
-import Tkinter
-
-try:
- Tkinter.Button()
-except Tkinter.TclError, msg:
- # assuming tk is not available
- raise unittest.SkipTest("tk not available: %s" % msg)
-
this_dir = os.path.dirname(os.path.abspath(__file__))
lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
'lib-tk', 'test'))
@@ -20,6 +11,9 @@
with test_support.DirsOnSysPath(lib_tk_test):
import runtktests
+# Skip test if tk cannot be initialized.
+runtktests.check_tk_availability()
+
def test_main(enable_gui=False):
if enable_gui:
if test_support.use_resources is None:
diff --git a/Lib/test/test_ttk_guionly.py b/Lib/test/test_ttk_guionly.py
index 60a57f0..e0368be 100644
--- a/Lib/test/test_ttk_guionly.py
+++ b/Lib/test/test_ttk_guionly.py
@@ -5,6 +5,16 @@
# Skip this test if _tkinter wasn't built.
test_support.import_module('_tkinter')
+this_dir = os.path.dirname(os.path.abspath(__file__))
+lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
+ 'lib-tk', 'test'))
+
+with test_support.DirsOnSysPath(lib_tk_test):
+ import runtktests
+
+# Skip test if tk cannot be initialized.
+runtktests.check_tk_availability()
+
import ttk
from _tkinter import TclError
@@ -14,13 +24,6 @@
# assuming ttk is not available
raise unittest.SkipTest("ttk not available: %s" % msg)
-this_dir = os.path.dirname(os.path.abspath(__file__))
-lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
- 'lib-tk', 'test'))
-
-with test_support.DirsOnSysPath(lib_tk_test):
- import runtktests
-
def test_main(enable_gui=False):
if enable_gui:
if test_support.use_resources is None:
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index bd43dbc..399eed7 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -5,9 +5,16 @@
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
-import sys, struct, codecs
+import sys
+import struct
+import codecs
+import unittest
from test import test_support, string_tests
+# decorator to skip tests on narrow builds
+requires_wide_build = unittest.skipIf(sys.maxunicode == 65535,
+ 'requires wide build')
+
# Error handling (bad decoder return)
def search_function(encoding):
def decode1(input, errors="strict"):
@@ -269,30 +276,106 @@
# Surrogates on both sides, no fixup required
self.assertTrue(u'\ud800\udc02' < u'\ud84d\udc56')
+ def test_capitalize(self):
+ string_tests.CommonTest.test_capitalize(self)
+ # check that titlecased chars are lowered correctly
+ # \u1ffc is the titlecased char
+ self.checkequal(u'\u1ffc\u1ff3\u1ff3\u1ff3',
+ u'\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
+ # check with cased non-letter chars
+ self.checkequal(u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
+ u'\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
+ self.checkequal(u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
+ u'\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
+ self.checkequal(u'\u2160\u2171\u2172',
+ u'\u2160\u2161\u2162', 'capitalize')
+ self.checkequal(u'\u2160\u2171\u2172',
+ u'\u2170\u2171\u2172', 'capitalize')
+ # check with Ll chars with no upper - nothing changes here
+ self.checkequal(u'\u019b\u1d00\u1d86\u0221\u1fb7',
+ u'\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
+
def test_islower(self):
string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
self.checkequalnofix(False, u'\u1FFc', 'islower')
+ @requires_wide_build
+ def test_islower_non_bmp(self):
+ # non-BMP, uppercase
+ self.assertFalse(u'\U00010401'.islower())
+ self.assertFalse(u'\U00010427'.islower())
+ # non-BMP, lowercase
+ self.assertTrue(u'\U00010429'.islower())
+ self.assertTrue(u'\U0001044E'.islower())
+ # non-BMP, non-cased
+ self.assertFalse(u'\U0001F40D'.islower())
+ self.assertFalse(u'\U0001F46F'.islower())
+
def test_isupper(self):
string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
if not sys.platform.startswith('java'):
self.checkequalnofix(False, u'\u1FFc', 'isupper')
+ @requires_wide_build
+ def test_isupper_non_bmp(self):
+ # non-BMP, uppercase
+ self.assertTrue(u'\U00010401'.isupper())
+ self.assertTrue(u'\U00010427'.isupper())
+ # non-BMP, lowercase
+ self.assertFalse(u'\U00010429'.isupper())
+ self.assertFalse(u'\U0001044E'.isupper())
+ # non-BMP, non-cased
+ self.assertFalse(u'\U0001F40D'.isupper())
+ self.assertFalse(u'\U0001F46F'.isupper())
+
def test_istitle(self):
- string_tests.MixinStrUnicodeUserStringTest.test_title(self)
+ string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
self.checkequalnofix(True, u'\u1FFc', 'istitle')
self.checkequalnofix(True, u'Greek \u1FFcitlecases ...', 'istitle')
+ @requires_wide_build
+ def test_istitle_non_bmp(self):
+ # non-BMP, uppercase + lowercase
+ self.assertTrue(u'\U00010401\U00010429'.istitle())
+ self.assertTrue(u'\U00010427\U0001044E'.istitle())
+ # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
+ for ch in [u'\U00010429', u'\U0001044E', u'\U0001F40D', u'\U0001F46F']:
+ self.assertFalse(ch.istitle(), '{!r} is not title'.format(ch))
+
def test_isspace(self):
string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
self.checkequalnofix(True, u'\u2000', 'isspace')
self.checkequalnofix(True, u'\u200a', 'isspace')
self.checkequalnofix(False, u'\u2014', 'isspace')
+ @requires_wide_build
+ def test_isspace_non_bmp(self):
+ # apparently there are no non-BMP spaces chars in Unicode 6
+ for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
+ u'\U0001F40D', u'\U0001F46F']:
+ self.assertFalse(ch.isspace(), '{!r} is not space.'.format(ch))
+
+ @requires_wide_build
+ def test_isalnum_non_bmp(self):
+ for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
+ u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
+ self.assertTrue(ch.isalnum(), '{!r} is alnum.'.format(ch))
+
def test_isalpha(self):
string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
self.checkequalnofix(True, u'\u1FFc', 'isalpha')
+ @requires_wide_build
+ def test_isalpha_non_bmp(self):
+ # non-BMP, cased
+ self.assertTrue(u'\U00010401'.isalpha())
+ self.assertTrue(u'\U00010427'.isalpha())
+ self.assertTrue(u'\U00010429'.isalpha())
+ self.assertTrue(u'\U0001044E'.isalpha())
+ # non-BMP, non-cased
+ self.assertFalse(u'\U0001F40D'.isalpha())
+ self.assertFalse(u'\U0001F46F'.isalpha())
+
def test_isdecimal(self):
self.checkequalnofix(False, u'', 'isdecimal')
self.checkequalnofix(False, u'a', 'isdecimal')
@@ -305,12 +388,28 @@
self.checkraises(TypeError, 'abc', 'isdecimal', 42)
+ @requires_wide_build
+ def test_isdecimal_non_bmp(self):
+ for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
+ u'\U0001F40D', u'\U0001F46F', u'\U00011065', u'\U0001F107']:
+ self.assertFalse(ch.isdecimal(), '{!r} is not decimal.'.format(ch))
+ for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0']:
+ self.assertTrue(ch.isdecimal(), '{!r} is decimal.'.format(ch))
+
def test_isdigit(self):
string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
self.checkequalnofix(True, u'\u2460', 'isdigit')
self.checkequalnofix(False, u'\xbc', 'isdigit')
self.checkequalnofix(True, u'\u0660', 'isdigit')
+ @requires_wide_build
+ def test_isdigit_non_bmp(self):
+ for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
+ u'\U0001F40D', u'\U0001F46F', u'\U00011065']:
+ self.assertFalse(ch.isdigit(), '{!r} is not a digit.'.format(ch))
+ for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
+ self.assertTrue(ch.isdigit(), '{!r} is a digit.'.format(ch))
+
def test_isnumeric(self):
self.checkequalnofix(False, u'', 'isnumeric')
self.checkequalnofix(False, u'a', 'isnumeric')
@@ -323,6 +422,109 @@
self.assertRaises(TypeError, u"abc".isnumeric, 42)
+ @requires_wide_build
+ def test_isnumeric_non_bmp(self):
+ for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
+ u'\U0001F40D', u'\U0001F46F']:
+ self.assertFalse(ch.isnumeric(), '{!r} is not numeric.'.format(ch))
+ for ch in [u'\U00010107', u'\U0001D7F6', u'\U00023b1b',
+ u'\U000104A0', u'\U0001F107']:
+ self.assertTrue(ch.isnumeric(), '{!r} is numeric.'.format(ch))
+
+ @requires_wide_build
+ def test_surrogates(self):
+ # this test actually passes on narrow too, but it's just by accident.
+ # Surrogates are seen as non-cased chars, so u'X\uD800X' is as
+ # uppercase as 'X X'
+ for s in (u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
+ u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
+ self.assertTrue(s.islower())
+ self.assertFalse(s.isupper())
+ self.assertFalse(s.istitle())
+ for s in (u'A\uD800B\uDFFF', u'A\uDFFFB\uD800',
+ u'A\uD800B\uDFFFA', u'A\uDFFFB\uD800A'):
+ self.assertFalse(s.islower())
+ self.assertTrue(s.isupper())
+ self.assertTrue(s.istitle())
+
+ for meth_name in ('islower', 'isupper', 'istitle'):
+ meth = getattr(unicode, meth_name)
+ for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF'):
+ self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
+
+ for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
+ 'isdecimal', 'isnumeric'):
+ meth = getattr(unicode, meth_name)
+ for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF',
+ u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
+ u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
+ self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
+
+
+ @requires_wide_build
+ def test_lower(self):
+ string_tests.CommonTest.test_lower(self)
+ self.assertEqual(u'\U00010427'.lower(), u'\U0001044F')
+ self.assertEqual(u'\U00010427\U00010427'.lower(),
+ u'\U0001044F\U0001044F')
+ self.assertEqual(u'\U00010427\U0001044F'.lower(),
+ u'\U0001044F\U0001044F')
+ self.assertEqual(u'X\U00010427x\U0001044F'.lower(),
+ u'x\U0001044Fx\U0001044F')
+
+ @requires_wide_build
+ def test_upper(self):
+ string_tests.CommonTest.test_upper(self)
+ self.assertEqual(u'\U0001044F'.upper(), u'\U00010427')
+ self.assertEqual(u'\U0001044F\U0001044F'.upper(),
+ u'\U00010427\U00010427')
+ self.assertEqual(u'\U00010427\U0001044F'.upper(),
+ u'\U00010427\U00010427')
+ self.assertEqual(u'X\U00010427x\U0001044F'.upper(),
+ u'X\U00010427X\U00010427')
+
+ @requires_wide_build
+ def test_capitalize(self):
+ string_tests.CommonTest.test_capitalize(self)
+ self.assertEqual(u'\U0001044F'.capitalize(), u'\U00010427')
+ self.assertEqual(u'\U0001044F\U0001044F'.capitalize(),
+ u'\U00010427\U0001044F')
+ self.assertEqual(u'\U00010427\U0001044F'.capitalize(),
+ u'\U00010427\U0001044F')
+ self.assertEqual(u'\U0001044F\U00010427'.capitalize(),
+ u'\U00010427\U0001044F')
+ self.assertEqual(u'X\U00010427x\U0001044F'.capitalize(),
+ u'X\U0001044Fx\U0001044F')
+
+ @requires_wide_build
+ def test_title(self):
+ string_tests.MixinStrUnicodeUserStringTest.test_title(self)
+ self.assertEqual(u'\U0001044F'.title(), u'\U00010427')
+ self.assertEqual(u'\U0001044F\U0001044F'.title(),
+ u'\U00010427\U0001044F')
+ self.assertEqual(u'\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
+ u'\U00010427\U0001044F \U00010427\U0001044F')
+ self.assertEqual(u'\U00010427\U0001044F \U00010427\U0001044F'.title(),
+ u'\U00010427\U0001044F \U00010427\U0001044F')
+ self.assertEqual(u'\U0001044F\U00010427 \U0001044F\U00010427'.title(),
+ u'\U00010427\U0001044F \U00010427\U0001044F')
+ self.assertEqual(u'X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
+ u'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
+
+ @requires_wide_build
+ def test_swapcase(self):
+ string_tests.CommonTest.test_swapcase(self)
+ self.assertEqual(u'\U0001044F'.swapcase(), u'\U00010427')
+ self.assertEqual(u'\U00010427'.swapcase(), u'\U0001044F')
+ self.assertEqual(u'\U0001044F\U0001044F'.swapcase(),
+ u'\U00010427\U00010427')
+ self.assertEqual(u'\U00010427\U0001044F'.swapcase(),
+ u'\U0001044F\U00010427')
+ self.assertEqual(u'\U0001044F\U00010427'.swapcase(),
+ u'\U00010427\U0001044F')
+ self.assertEqual(u'X\U00010427x\U0001044F'.swapcase(),
+ u'x\U0001044FX\U00010427')
+
def test_contains(self):
# Testing Unicode contains method
self.assertIn('a', u'abdb')
diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py
index e7e54a2..3f644fb 100644
--- a/Lib/test/test_urllib.py
+++ b/Lib/test/test_urllib.py
@@ -114,6 +114,9 @@
proxies = urllib.getproxies_environment()
# getproxies_environment use lowered case truncated (no '_proxy') keys
self.assertEqual('localhost', proxies['no'])
+ # List of no_proxies with space.
+ self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
+ self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com'))
class urlopen_HttpTests(unittest.TestCase):
@@ -404,6 +407,7 @@
result = urllib.quote(partial_quote)
self.assertEqual(expected, result,
"using quote(): %s != %s" % (expected, result))
+ result = urllib.quote_plus(partial_quote)
self.assertEqual(expected, result,
"using quote_plus(): %s != %s" % (expected, result))
self.assertRaises(TypeError, urllib.quote, None)
diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
index e96f948..e247315 100644
--- a/Lib/test/test_urllib2.py
+++ b/Lib/test/test_urllib2.py
@@ -293,6 +293,7 @@
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
+
def request(self, method, url, body=None, headers=None):
self.method = method
self.selector = url
@@ -304,9 +305,13 @@
if self.raise_on_endheaders:
import socket
raise socket.error()
+
def getresponse(self):
return MockHTTPResponse(MockFile(), {}, 200, "OK")
+ def close(self):
+ pass
+
class MockHandler:
# useful for testing handler machinery
# see add_ordered_mock_handlers() docstring
@@ -606,6 +611,7 @@
def retrfile(self, filename, filetype):
self.filename, self.filetype = filename, filetype
return StringIO.StringIO(self.data), len(self.data)
+ def close(self): pass
class NullFTPHandler(urllib2.FTPHandler):
def __init__(self, data): self.data = data
diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py
index 867fcfa..bd2c467 100644
--- a/Lib/test/test_urllib2net.py
+++ b/Lib/test/test_urllib2net.py
@@ -186,6 +186,16 @@
opener.open(request)
self.assertEqual(request.get_header('User-agent'),'Test-Agent')
+ def test_sites_no_connection_close(self):
+ # Some sites do not send Connection: close header.
+ # Verify that those work properly. (#issue12576)
+
+ URL = 'http://www.imdb.com' # No Connection:close
+ with test_support.transient_internet(URL):
+ req = urllib2.urlopen(URL)
+ res = req.read()
+ self.assertTrue(res)
+
def _test_urls(self, urls, handlers, retry=True):
import time
import logging
@@ -231,6 +241,7 @@
handlers = []
cfh = urllib2.CacheFTPHandler()
+ self.addCleanup(cfh.clear_cache)
cfh.setTimeout(1)
handlers.append(cfh)
diff --git a/Lib/test/test_urllibnet.py b/Lib/test/test_urllibnet.py
index 8cba2dc..1d88331 100644
--- a/Lib/test/test_urllibnet.py
+++ b/Lib/test/test_urllibnet.py
@@ -131,6 +131,14 @@
def test_bad_address(self):
# Make sure proper exception is raised when connecting to a bogus
# address.
+ bogus_domain = "sadflkjsasf.i.nvali.d"
+ try:
+ socket.gethostbyname(bogus_domain)
+ except socket.gaierror:
+ pass
+ else:
+ # This happens with some overzealous DNS providers such as OpenDNS
+ self.skipTest("%r should not resolve for test to work" % bogus_domain)
self.assertRaises(IOError,
# SF patch 809915: In Sep 2003, VeriSign started
# highjacking invalid .com and .net addresses to
diff --git a/Lib/test/test_urlparse.py b/Lib/test/test_urlparse.py
index 9961485..c690a67 100644
--- a/Lib/test/test_urlparse.py
+++ b/Lib/test/test_urlparse.py
@@ -82,7 +82,12 @@
def test_qsl(self):
for orig, expect in parse_qsl_test_cases:
result = urlparse.parse_qsl(orig, keep_blank_values=True)
- self.assertEqual(result, expect, "Error parsing %s" % repr(orig))
+ self.assertEqual(result, expect, "Error parsing %r" % orig)
+ expect_without_blanks = [v for v in expect if len(v[1])]
+ result = urlparse.parse_qsl(orig, keep_blank_values=False)
+ self.assertEqual(result, expect_without_blanks,
+ "Error parsing %r" % orig)
+
def test_roundtrips(self):
testcases = [
@@ -331,6 +336,11 @@
self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y')
self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y')
self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
+ self.checkJoin('http:///', '..','http:///')
+ self.checkJoin('', 'http://a/b/c/g?y/./x','http://a/b/c/g?y/./x')
+ self.checkJoin('', 'http://a/./g', 'http://a/./g')
+ self.checkJoin('svn://pathtorepo/dir1','dir2','svn://pathtorepo/dir2')
+ self.checkJoin('svn+ssh://pathtorepo/dir1','dir2','svn+ssh://pathtorepo/dir2')
def test_RFC2732(self):
for url, hostname, port in [
@@ -505,7 +515,6 @@
self.assertEqual(urlparse.urlparse("http://www.python.org:80"),
('http','www.python.org:80','','','',''))
-
def test_main():
test_support.run_unittest(UrlParseTestCase)
diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py
index 5c4fa59..e502ed8 100644
--- a/Lib/test/test_warnings.py
+++ b/Lib/test/test_warnings.py
@@ -530,6 +530,18 @@
assert expected_line
self.assertEqual(second_line, expected_line)
+ def test_filename_none(self):
+ # issue #12467: race condition if a warning is emitted at shutdown
+ globals_dict = globals()
+ oldfile = globals_dict['__file__']
+ try:
+ with original_warnings.catch_warnings(module=self.module) as w:
+ self.module.filterwarnings("always", category=UserWarning)
+ globals_dict['__file__'] = None
+ self.module.warn('test', UserWarning)
+ finally:
+ globals_dict['__file__'] = oldfile
+
class WarningsDisplayTests(unittest.TestCase):
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index 78a6a92..474a4b4 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -1,6 +1,8 @@
# xml.etree test for cElementTree
from test import test_support
+from test.test_support import precisionbigmemtest, _2G
+import unittest
cET = test_support.import_module('xml.etree.cElementTree')
@@ -15,6 +17,20 @@
"""
+class MiscTests(unittest.TestCase):
+ # Issue #8651.
+ @precisionbigmemtest(size=_2G + 100, memuse=1)
+ def test_length_overflow(self, size):
+ if size < _2G + 100:
+ self.skipTest("not enough free memory, need at least 2 GB")
+ data = b'x' * size
+ parser = cET.XMLParser()
+ try:
+ self.assertRaises(OverflowError, parser.feed, data)
+ finally:
+ data = None
+
+
def test_main():
from test import test_xml_etree, test_xml_etree_c
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
index 6310c97..79100e9 100644
--- a/Lib/test/test_xmlrpc.py
+++ b/Lib/test/test_xmlrpc.py
@@ -472,6 +472,9 @@
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
+ def test_unicode_host(self):
+ server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
+ self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
# [ch] The test 404 is causing lots of false alarms.
def XXXtest_404(self):
diff --git a/Lib/test/test_xpickle.py b/Lib/test/test_xpickle.py
index 2ce1dcb..ac3a33f 100644
--- a/Lib/test/test_xpickle.py
+++ b/Lib/test/test_xpickle.py
@@ -154,6 +154,10 @@
def test_unicode_high_plane(self):
pass
+ # 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.
diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py
index c4a64a3..6cba26c 100644
--- a/Lib/test/test_zipfile.py
+++ b/Lib/test/test_zipfile.py
@@ -335,6 +335,24 @@
with zipfile.ZipFile(f, "r") as zipfp:
self.assertEqual(zipfp.namelist(), [TESTFN])
+ def test_ignores_newline_at_end(self):
+ with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
+ zipfp.write(TESTFN, TESTFN)
+ with open(TESTFN2, 'a') as f:
+ f.write("\r\n\00\00\00")
+ with zipfile.ZipFile(TESTFN2, "r") as zipfp:
+ self.assertIsInstance(zipfp, zipfile.ZipFile)
+
+ def test_ignores_stuff_appended_past_comments(self):
+ with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
+ zipfp.comment = b"this is a comment"
+ zipfp.write(TESTFN, TESTFN)
+ with open(TESTFN2, 'a') as f:
+ f.write("abcdef\r\n")
+ with zipfile.ZipFile(TESTFN2, "r") as zipfp:
+ self.assertIsInstance(zipfp, zipfile.ZipFile)
+ self.assertEqual(zipfp.comment, b"this is a comment")
+
def test_write_default_name(self):
"""Check that calling ZipFile.write without arcname specified
produces the expected result."""
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index 5974c8b..a66738a 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -25,11 +25,6 @@
from traceback import extract_tb, extract_stack, print_tb
raise_src = 'def do_raise(): raise TypeError\n'
-# so we only run testAFakeZlib once if this test is run repeatedly
-# which happens when we look for ref leaks
-test_imported = False
-
-
def make_pyc(co, mtime):
data = marshal.dumps(co)
if type(mtime) is type(0.0):
@@ -463,19 +458,7 @@
zipimport._zip_directory_cache.clear()
-def cleanup():
- # this is necessary if test is run repeated (like when finding leaks)
- global test_imported
- if test_imported:
- zipimport._zip_directory_cache.clear()
- if hasattr(UncompressedZipImportTestCase, 'testAFakeZlib'):
- delattr(UncompressedZipImportTestCase, 'testAFakeZlib')
- if hasattr(CompressedZipImportTestCase, 'testAFakeZlib'):
- delattr(CompressedZipImportTestCase, 'testAFakeZlib')
- test_imported = True
-
def test_main():
- cleanup()
try:
test_support.run_unittest(
UncompressedZipImportTestCase,
diff --git a/Lib/test/test_zlib.py b/Lib/test/test_zlib.py
index cbc3ed4..7f63143 100644
--- a/Lib/test/test_zlib.py
+++ b/Lib/test/test_zlib.py
@@ -1,10 +1,16 @@
import unittest
-from test import test_support
+from test.test_support import TESTFN, run_unittest, import_module, unlink, requires
import binascii
import random
-from test.test_support import precisionbigmemtest, _1G
+from test.test_support import precisionbigmemtest, _1G, _4G
+import sys
-zlib = test_support.import_module('zlib')
+try:
+ import mmap
+except ImportError:
+ mmap = None
+
+zlib = import_module('zlib')
class ChecksumTestCase(unittest.TestCase):
@@ -304,6 +310,15 @@
self.assertRaises(ValueError, dco.decompress, "", -1)
self.assertEqual('', dco.unconsumed_tail)
+ def test_clear_unconsumed_tail(self):
+ # Issue #12050: calling decompress() without providing max_length
+ # should clear the unconsumed_tail attribute.
+ cdata = "x\x9cKLJ\x06\x00\x02M\x01" # "abc"
+ dco = zlib.decompressobj()
+ ddata = dco.decompress(cdata, 1)
+ ddata += dco.decompress(dco.unconsumed_tail)
+ self.assertEqual(dco.unconsumed_tail, "")
+
def test_flushes(self):
# Test flush() with the various options, using all the
# different levels in order to provide more variations.
@@ -546,7 +561,7 @@
def test_main():
- test_support.run_unittest(
+ run_unittest(
ChecksumTestCase,
ExceptionTestCase,
CompressTestCase,
diff --git a/Lib/timeit.py b/Lib/timeit.py
index a095313..da9e819 100644
--- a/Lib/timeit.py
+++ b/Lib/timeit.py
@@ -191,9 +191,11 @@
it = [None] * number
gcold = gc.isenabled()
gc.disable()
- timing = self.inner(it, self.timer)
- if gcold:
- gc.enable()
+ try:
+ timing = self.inner(it, self.timer)
+ finally:
+ if gcold:
+ gc.enable()
return timing
def repeat(self, repeat=default_repeat, number=default_number):
diff --git a/Lib/trace.py b/Lib/trace.py
index 6e15e8b..38a13e2 100644
--- a/Lib/trace.py
+++ b/Lib/trace.py
@@ -502,15 +502,7 @@
def run(self, cmd):
import __main__
dict = __main__.__dict__
- if not self.donothing:
- threading.settrace(self.globaltrace)
- sys.settrace(self.globaltrace)
- try:
- exec cmd in dict, dict
- finally:
- if not self.donothing:
- sys.settrace(None)
- threading.settrace(None)
+ self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals=None, locals=None):
if globals is None: globals = {}
diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py
index dcaae93..4b3839e 100644
--- a/Lib/unittest/case.py
+++ b/Lib/unittest/case.py
@@ -196,12 +196,12 @@
# instances of said type in more detail to generate a more useful
# error message.
self._type_equality_funcs = {}
- self.addTypeEqualityFunc(dict, self.assertDictEqual)
- self.addTypeEqualityFunc(list, self.assertListEqual)
- self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
- self.addTypeEqualityFunc(set, self.assertSetEqual)
- self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
- self.addTypeEqualityFunc(unicode, self.assertMultiLineEqual)
+ self.addTypeEqualityFunc(dict, 'assertDictEqual')
+ self.addTypeEqualityFunc(list, 'assertListEqual')
+ self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
+ self.addTypeEqualityFunc(set, 'assertSetEqual')
+ self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
+ self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
def addTypeEqualityFunc(self, typeobj, function):
"""Add a type specific assertEqual style function to compare a type.
@@ -490,6 +490,8 @@
if type(first) is type(second):
asserter = self._type_equality_funcs.get(type(first))
if asserter is not None:
+ if isinstance(asserter, basestring):
+ asserter = getattr(self, asserter)
return asserter
return self._baseAssertEqual
diff --git a/Lib/unittest/test/test_case.py b/Lib/unittest/test/test_case.py
index 2e449c5..e92b019 100644
--- a/Lib/unittest/test/test_case.py
+++ b/Lib/unittest/test/test_case.py
@@ -1,5 +1,6 @@
import difflib
import pprint
+import pickle
import re
import sys
@@ -1104,6 +1105,20 @@
self.assertEqual(len(result.errors), 1)
self.assertEqual(result.testsRun, 1)
+ def testPickle(self):
+ # Issue 10326
+
+ # Can't use TestCase classes defined in Test class as
+ # pickle does not work with inner classes
+ test = unittest.TestCase('run')
+ for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+
+ # blew up prior to fix
+ pickled_test = pickle.dumps(test, protocol=protocol)
+
+ unpickled_test = pickle.loads(pickled_test)
+ self.assertEqual(test, unpickled_test)
+
if __name__ == '__main__':
unittest.main()
diff --git a/Lib/unittest/test/test_result.py b/Lib/unittest/test/test_result.py
index f0f3a63..eb68c1d 100644
--- a/Lib/unittest/test/test_result.py
+++ b/Lib/unittest/test/test_result.py
@@ -503,7 +503,7 @@
class Foo(unittest.TestCase):
@classmethod
def setUpClass(cls):
- 1/0
+ 1//0
def test_foo(self):
pass
suite = unittest.TestSuite([Foo('test_foo')])
@@ -517,7 +517,7 @@
class Foo(unittest.TestCase):
@classmethod
def tearDownClass(cls):
- 1/0
+ 1//0
def test_foo(self):
pass
suite = unittest.TestSuite([Foo('test_foo')])
@@ -534,7 +534,7 @@
class Module(object):
@staticmethod
def setUpModule():
- 1/0
+ 1//0
Foo.__module__ = 'Module'
sys.modules['Module'] = Module
@@ -553,7 +553,7 @@
class Module(object):
@staticmethod
def tearDownModule():
- 1/0
+ 1//0
Foo.__module__ = 'Module'
sys.modules['Module'] = Module
diff --git a/Lib/urllib.py b/Lib/urllib.py
index 62c08c9..1d65ce5 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -850,13 +850,16 @@
"""Class used by open_ftp() for cache of open FTP connections."""
def __init__(self, user, passwd, host, port, dirs,
- timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
+ timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
+ persistent=True):
self.user = user
self.passwd = passwd
self.host = host
self.port = port
self.dirs = dirs
self.timeout = timeout
+ self.refcount = 0
+ self.keepalive = persistent
self.init()
def init(self):
@@ -883,7 +886,7 @@
# Try to retrieve as a file
try:
cmd = 'RETR ' + file
- conn = self.ftp.ntransfercmd(cmd)
+ conn, retrlen = self.ftp.ntransfercmd(cmd)
except ftplib.error_perm, reason:
if str(reason)[:3] != '550':
raise IOError, ('ftp error', reason), sys.exc_info()[2]
@@ -903,11 +906,14 @@
cmd = 'LIST ' + file
else:
cmd = 'LIST'
- conn = self.ftp.ntransfercmd(cmd)
+ conn, retrlen = self.ftp.ntransfercmd(cmd)
self.busy = 1
+ ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
+ self.refcount += 1
+ conn.close()
# Pass back both a suitably decorated object and a retrieval length
- return (addclosehook(conn[0].makefile('rb'),
- self.endtransfer), conn[1])
+ return (ftpobj, retrlen)
+
def endtransfer(self):
if not self.busy:
return
@@ -918,6 +924,17 @@
pass
def close(self):
+ self.keepalive = False
+ if self.refcount <= 0:
+ self.real_close()
+
+ def file_close(self):
+ self.endtransfer()
+ self.refcount -= 1
+ if self.refcount <= 0 and not self.keepalive:
+ self.real_close()
+
+ def real_close(self):
self.endtransfer()
try:
self.ftp.close()
@@ -1349,7 +1366,8 @@
# strip port off host
hostonly, port = splitport(host)
# check if the host ends with any of the DNS suffixes
- for name in no_proxy.split(','):
+ no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')]
+ for name in no_proxy_list:
if name and (hostonly.endswith(name) or host.endswith(name)):
return 1
# otherwise, don't bypass
@@ -1581,66 +1599,3 @@
# Report during remote transfers
print "Block number: %d, Block size: %d, Total size: %d" % (
blocknum, blocksize, totalsize)
-
-# Test program
-def test(args=[]):
- if not args:
- args = [
- '/etc/passwd',
- 'file:/etc/passwd',
- 'file://localhost/etc/passwd',
- 'ftp://ftp.gnu.org/pub/README',
- 'http://www.python.org/index.html',
- ]
- if hasattr(URLopener, "open_https"):
- args.append('https://synergy.as.cmu.edu/~geek/')
- try:
- for url in args:
- print '-'*10, url, '-'*10
- fn, h = urlretrieve(url, None, reporthook)
- print fn
- if h:
- print '======'
- for k in h.keys(): print k + ':', h[k]
- print '======'
- with open(fn, 'rb') as fp:
- data = fp.read()
- if '\r' in data:
- table = string.maketrans("", "")
- data = data.translate(table, "\r")
- print data
- fn, h = None, None
- print '-'*40
- finally:
- urlcleanup()
-
-def main():
- import getopt, sys
- try:
- opts, args = getopt.getopt(sys.argv[1:], "th")
- except getopt.error, msg:
- print msg
- print "Use -h for help"
- return
- t = 0
- for o, a in opts:
- if o == '-t':
- t = t + 1
- if o == '-h':
- print "Usage: python urllib.py [-t] [url ...]"
- print "-t runs self-test;",
- print "otherwise, contents of urls are printed"
- return
- if t:
- if t > 1:
- test1()
- test(args)
- else:
- if not args:
- print "Use -h for help"
- for url in args:
- print urlopen(url).read(),
-
-# Run test program when run as a script
-if __name__ == '__main__':
- main()
diff --git a/Lib/urllib2.py b/Lib/urllib2.py
index abc84b1..a0065b5 100644
--- a/Lib/urllib2.py
+++ b/Lib/urllib2.py
@@ -1166,12 +1166,14 @@
try:
h.request(req.get_method(), req.get_selector(), req.data, headers)
+ except socket.error, err: # XXX what error?
+ h.close()
+ raise URLError(err)
+ else:
try:
r = h.getresponse(buffering=True)
- except TypeError: #buffering kw not supported
+ except TypeError: # buffering kw not supported
r = h.getresponse()
- except socket.error, err: # XXX what error?
- raise URLError(err)
# Pick apart the HTTPResponse object to get the addinfourl
# object initialized properly.
@@ -1397,7 +1399,8 @@
raise URLError, ('ftp error: %s' % msg), sys.exc_info()[2]
def connect_ftp(self, user, passwd, host, port, dirs, timeout):
- fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
+ fw = ftpwrapper(user, passwd, host, port, dirs, timeout,
+ persistent=False)
## fw.ftp.set_debuglevel(1)
return fw
@@ -1446,3 +1449,9 @@
del self.timeout[k]
break
self.soonest = min(self.timeout.values())
+
+ def clear_cache(self):
+ for conn in self.cache.values():
+ conn.close()
+ self.cache.clear()
+ self.timeout.clear()
diff --git a/Lib/urlparse.py b/Lib/urlparse.py
index e5528fa..b42e0f4 100644
--- a/Lib/urlparse.py
+++ b/Lib/urlparse.py
@@ -34,7 +34,8 @@
# A classification of schemes ('' means apply by default)
uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap',
'wais', 'file', 'https', 'shttp', 'mms',
- 'prospero', 'rtsp', 'rtspu', '', 'sftp']
+ 'prospero', 'rtsp', 'rtspu', '', 'sftp',
+ 'svn', 'svn+ssh']
uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet',
'imap', 'wais', 'file', 'mms', 'https', 'shttp',
'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '',
diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py
index 41fd175..f3c53d4 100644
--- a/Lib/webbrowser.py
+++ b/Lib/webbrowser.py
@@ -237,7 +237,7 @@
stdout=(self.redirect_stdout and inout or None),
stderr=inout, preexec_fn=setsid)
if remote:
- # wait five secons. If the subprocess is not finished, the
+ # wait five seconds. If the subprocess is not finished, the
# remote invocation has (hopefully) started a new instance.
time.sleep(1)
rc = p.poll()
diff --git a/Lib/whichdb.py b/Lib/whichdb.py
index f077f87..9071430 100644
--- a/Lib/whichdb.py
+++ b/Lib/whichdb.py
@@ -91,7 +91,7 @@
return ""
# Check for GNU dbm
- if magic == 0x13579ace:
+ if magic in (0x13579ace, 0x13579acd, 0x13579acf):
return "gdbm"
# Check for old Berkeley db hash file format v2
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
index 7518852..a1f6f63 100644
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -806,7 +806,9 @@
_write_data(writer, attrs[a_name].value)
writer.write("\"")
if self.childNodes:
- writer.write(">%s"%(newl))
+ writer.write(">")
+ if self.childNodes[0].nodeType != Node.TEXT_NODE:
+ writer.write(newl)
for node in self.childNodes:
node.writexml(writer,indent+addindent,addindent,newl)
writer.write("%s</%s>%s" % (indent,self.tagName,newl))
@@ -1031,7 +1033,7 @@
return newText
def writexml(self, writer, indent="", addindent="", newl=""):
- _write_data(writer, "%s%s%s"%(indent, self.data, newl))
+ _write_data(writer, self.data)
# DOM Level 3 (WD 9 April 2002)
diff --git a/Lib/xml/parsers/expat.py b/Lib/xml/parsers/expat.py
index 11359a0..00b5c78 100644
--- a/Lib/xml/parsers/expat.py
+++ b/Lib/xml/parsers/expat.py
@@ -1,4 +1,4 @@
"""Interface to the Expat non-validating XML parser."""
-__version__ = '$Revision$'
+__version__ = '$Revision: 17640 $'
from pyexpat import *
diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py
index 3cba39f..653c424 100644
--- a/Lib/xmlrpclib.py
+++ b/Lib/xmlrpclib.py
@@ -1539,6 +1539,9 @@
allow_none=0, use_datetime=0):
# establish a "logical" server connection
+ if isinstance(uri, unicode):
+ uri = uri.encode('ISO-8859-1')
+
# get the url
import urllib
type, uri = urllib.splittype(uri)
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index 7e3caf0..f876f42 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -236,16 +236,14 @@
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
endrec = list(struct.unpack(structEndArchive, recData))
- comment = data[start+sizeEndCentDir:]
- # check that comment length is correct
- if endrec[_ECD_COMMENT_SIZE] == len(comment):
- # Append the archive comment and start offset
- endrec.append(comment)
- endrec.append(maxCommentStart + start)
+ commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
+ comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
+ endrec.append(comment)
+ endrec.append(maxCommentStart + start)
- # Try to read the "Zip64 end of central directory" structure
- return _EndRecData64(fpin, maxCommentStart + start - filesize,
- endrec)
+ # Try to read the "Zip64 end of central directory" structure
+ return _EndRecData64(fpin, maxCommentStart + start - filesize,
+ endrec)
# Unable to find a valid end of central directory structure
return
diff --git a/Mac/Makefile.in b/Mac/Makefile.in
index 5ab0ae5..0e4e070 100644
--- a/Mac/Makefile.in
+++ b/Mac/Makefile.in
@@ -77,6 +77,13 @@
do \
ln -fs "$(prefix)/bin/$${fn}" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/$${fn}" ;\
done
+ifneq ($(LIPO_32BIT_FLAGS),)
+ for fn in python-32 pythonw-32 \
+ python$(VERSION)-32 pythonw$(VERSION)-32 ;\
+ do \
+ ln -fs "$(prefix)/bin/$${fn}" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/$${fn}" ;\
+ done
+endif
#
@@ -91,6 +98,12 @@
do \
ln -fs "$(prefix)/bin/$${fn}" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/$${fn}" ;\
done
+ifneq ($(LIPO_32BIT_FLAGS),)
+ for fn in python$(VERSION)-32 pythonw$(VERSION)-32 ;\
+ do \
+ ln -fs "$(prefix)/bin/$${fn}" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/$${fn}" ;\
+ done
+endif
ln -fs "$(prefix)/bin/2to3-$(VERSION)" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/2to3-$(VERSION)" ;\
# By default most tools are installed without a version in their basename, to
diff --git a/Makefile.pre.in b/Makefile.pre.in
index 41745f5..c44bf1b 100644
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -853,8 +853,8 @@
plat-mac/lib-scriptpackages/Terminal
PLATMACPATH=:plat-mac:plat-mac/lib-scriptpackages
LIBSUBDIRS= lib-tk lib-tk/test lib-tk/test/test_tkinter \
- lib-tk/test/test_ttk site-packages test test/data \
- test/decimaltestdata test/xmltestdata \
+ lib-tk/test/test_ttk site-packages test test/data \
+ test/cjkencodings test/decimaltestdata test/xmltestdata test/subprocessdata \
test/tracedmodules \
encodings compiler hotshot \
email email/mime email/test email/test/data \
@@ -869,7 +869,7 @@
unittest unittest/test \
lib-old \
curses pydoc_data $(MACHDEPS)
-libinstall: build_all $(srcdir)/Lib/$(PLATDIR)
+libinstall: build_all $(srcdir)/Lib/$(PLATDIR) $(srcdir)/Modules/xxmodule.c
@for i in $(SCRIPTDIR) $(LIBDEST); \
do \
if test ! -d $(DESTDIR)$$i; then \
@@ -925,6 +925,10 @@
done; \
done
$(INSTALL_DATA) $(srcdir)/LICENSE $(DESTDIR)$(LIBDEST)/LICENSE.txt
+ if test -d $(DESTDIR)$(LIBDEST)/distutils/tests; then \
+ $(INSTALL_DATA) $(srcdir)/Modules/xxmodule.c \
+ $(DESTDIR)$(LIBDEST)/distutils/tests ; \
+ fi
PYTHONPATH=$(DESTDIR)$(LIBDEST) $(RUNSHARED) \
./$(BUILDPYTHON) -Wi -tt $(DESTDIR)$(LIBDEST)/compileall.py \
-d $(LIBDEST) -f \
@@ -1218,7 +1222,7 @@
# Find files with funny names
funny:
- find $(DISTDIRS) -type d \
+ find $(SUBDIRS) $(SUBDIRSTOO) -type d \
-o -name '*.[chs]' \
-o -name '*.py' \
-o -name '*.doc' \
diff --git a/Misc/ACKS b/Misc/ACKS
index 450a3a5..856afaa 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -147,6 +147,7 @@
Tom Christiansen
Vadim Chugunov
David Cinege
+Craig Citro
Mike Clarkson
Andrew Clegg
Brad Clements
@@ -162,6 +163,7 @@
Juan José Conti
Matt Conway
David M. Cooke
+Garrett Cooper
Greg Copeland
Aldo Cortesi
David Costanzo
@@ -193,6 +195,7 @@
Vincent Delft
Arnaud Delobelle
Erik Demaine
+John Dennis
Roger Dev
Raghuram Devarakonda
Catherine Devlin
@@ -243,6 +246,7 @@
Tim Everett
Paul Everitt
David Everly
+Daniel Evers
Greg Ewing
Martijn Faassen
Clovis Fabricio
@@ -306,6 +310,7 @@
Eddy De Greef
Duncan Grisby
Fabian Groffen
+John S. Gruber
Dag Gruneau
Filip Gruszczyński
Michael Guravage
@@ -337,6 +342,7 @@
Lance Finn Helsten
Jonathan Hendry
James Henstridge
+Kasun Herath
Chris Herborth
Ivan Herman
Jürgen Hermann
@@ -380,6 +386,7 @@
Jeremy Hylton
Gerhard Häring
Fredrik Håård
+Catalin Iacob
Mihai Ibanescu
Lars Immisch
Bobby Impollonia
@@ -396,6 +403,7 @@
Geert Jansen
Jack Jansen
Bill Janssen
+Thomas Jarosch
Drew Jenkins
Flemming Kjær Jensen
Jiba
@@ -428,6 +436,7 @@
Randall Kern
Magnus Kessler
Lawrence Kesteloot
+Rafe Kettler
Vivek Khera
Akira Kitada
Mads Kiilerich
@@ -440,6 +449,8 @@
Bastian Kleineidam
Bob Kline
Matthias Klose
+Jeremy Kloth
+Thomas Kluyver
Kim Knapp
Lenny Kneler
Pat Knight
@@ -456,7 +467,9 @@
Andrej Krpic
Ivan Krstić
Andrew Kuchling
+Ralf W. Grosse-Kunstleve
Vladimir Kushnir
+Kirill Kuzminykh (Кирилл Кузьминых)
Ross Lagerwall
Cameron Laird
Łukasz Langa
@@ -562,6 +575,7 @@
Derek Morr
James A Morrison
Pablo Mouzo
+Ruslan Mstoi
Sjoerd Mullender
Sape Mullender
Michael Muller
@@ -603,6 +617,7 @@
Jason Orendorff
Douglas Orr
Michele Orrù
+Oleg Oshmyan
Denis S. Otkidach
Michael Otteneder
R. M. Oudkerk
@@ -664,6 +679,7 @@
Marc Recht
John Redford
Terry Reedy
+Gareth Rees
Steve Reeves
Lennart Regebro
Ofir Reichenberg
@@ -678,7 +694,9 @@
Armin Rigo
Nicholas Riley
Jean-Claude Rimbault
+Vlad Riscutia
Juan M. Bello Rivas
+Davide Rizzo
Anthony Roach
Mark Roberts
Jim Robinson
@@ -706,6 +724,7 @@
Mark Russell
Nick Russo
Sébastien Sablé
+Suman Saha
Hajime Saitou
George Sakkis
Rich Salz
@@ -761,6 +780,7 @@
Paul Sokolovsky
Cody Somerville
Clay Spence
+Stefan Sperling
Per Spilling
Joshua Spoerri
Noah Spurrier
@@ -780,6 +800,7 @@
Patrick Strawderman
Dan Stromberg
Daniel Stutzbach
+Andreas Stührk
Nathan Sullivan
Mark Summerfield
Hisao Suzuki
@@ -797,9 +818,12 @@
Amy Taylor
Anatoly Techtonik
Mikhail Terekhov
+Richard M. Tew
Tobias Thelen
+Nicolas M. Thiéry
James Thomas
Robin Thomas
+Stephen Thorne
Eric Tiedemann
Tracy Tims
Oren Tirosh
diff --git a/Misc/NEWS b/Misc/NEWS
index 4c57348..2fbd70e 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -1,7 +1,7 @@
Python News
+++++++++++
-What's New in Python 2.7.2?
+What's New in Python 2.7.3?
===========================
*Release date: XXXX-XX-XX*
@@ -9,6 +9,357 @@
Core and Builtins
-----------------
+- Issue #7732: Fix a crash on importing a module if a directory has the same
+ name than a Python module (e.g. "__init__.py"): don't close the file twice.
+
+- Issue #12973: Fix overflow checks that invoked undefined behaviour in
+ int.__pow__. These overflow checks were causing int.__pow__ to produce
+ incorrect results with recent versions of Clang, as a result of the
+ compiler optimizing the check away. Also fix similar overflow checks
+ in list_repeat (listobject.c) and islice_next (itertoolsmodule.c). These
+ bugs caused test failures with recent versions of Clang.
+
+- Issue #12266: Fix str.capitalize() to correctly uppercase/lowercase
+ titlecased and cased non-letter characters.
+
+- Issues #12610 and #12609: Verify that user generated AST has correct string
+ and identifier types before compiling.
+
+- Issue #11627: Fix segfault when __new__ on a exception returns a
+ non-exception class.
+
+- Issue #12149: Update the method cache after a type's dictionnary gets
+ cleared by the garbage collector. This fixes a segfault when an instance
+ and its type get caught in a reference cycle, and the instance's
+ deallocator calls one of the methods on the type (e.g. when subclassing
+ IOBase). Diagnosis and patch by Davide Rizzo.
+
+- Issue #12501: Adjust callable() warning: callable() is only not supported in
+ Python 3.1. callable() is again supported in Python 3.2.
+
+- Issue #9611, #9015: FileIO.read(), FileIO.readinto(), FileIO.write() and
+ os.write() clamp the length to INT_MAX on Windows.
+
+- Issue #1195: my_fgets() now always clears errors before calling fgets(). Fix
+ the following case: sys.stdin.read() stopped with CTRL+d (end of file),
+ raw_input() interrupted by CTRL+c.
+
+- dict_proxy objects now display their contents rather than just the class
+ name.
+
+Library
+-------
+
+- Issue #13114: Fix the distutils commands check and register when the
+ long description is a Unicode string with non-ASCII characters.
+
+- Issue #7367: Fix pkgutil.walk_paths to skip directories whose
+ contents cannot be read.
+
+- Issue #7425: Prevent pydoc -k failures due to module import errors.
+ (Backport to 2.7 of existing 3.x fix)
+
+- Issue #13099: Fix sqlite3.Cursor.lastrowid under a Turkish locale.
+ Reported and diagnosed by Thomas Kluyver.
+
+- Issue #7689: Allow pickling of dynamically created classes when their
+ metaclass is registered with copy_reg. Patch by Nicolas M. Thiéry and
+ Craig Citro.
+
+- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by
+ Thomas Jarosch.
+
+- Issue #12931: xmlrpclib now encodes Unicode URI to ISO-8859-1, instead of
+ failing with a UnicodeDecodeError.
+
+- Issue #8933: distutils' PKG-INFO files will now correctly report
+ Metadata-Version: 1.1 instead of 1.0 if a Classifier or Download-URL field is
+ present.
+
+- Issue #8286: The distutils command sdist will print a warning message instead
+ of crashing when an invalid path is given in the manifest template.
+
+- Issue #12841: tarfile unnecessarily checked the existence of numerical user
+ and group ids on extraction. If one of them did not exist the respective id
+ of the current user (i.e. root) was used for the file and ownership
+ information was lost.
+
+- Issue #10946: The distutils commands bdist_dumb, bdist_wininst and bdist_msi
+ now respect a --skip-build option given to bdist.
+
+- Issue #12287: Fix a stack corruption in ossaudiodev module when the FD is
+ greater than FD_SETSIZE.
+
+- Issue #12839: Fix crash in zlib module due to version mismatch.
+ Fix by Richard M. Tew.
+
+- Issue #12786: Set communication pipes used by subprocess.Popen CLOEXEC to
+ avoid them being inherited by other subprocesses.
+
+- Issue #4106: Fix occasional exceptions printed out by multiprocessing on
+ interpreter shutdown.
+
+- Issue #11657: Fix sending file descriptors over 255 over a multiprocessing
+ Pipe.
+
+- Issue #12213: Fix a buffering bug with interleaved reads and writes that
+ could appear on io.BufferedRandom streams.
+
+- Issue #12326: sys.platform is now always 'linux2' on Linux, even if Python
+ is compiled on Linux 3.
+
+- Issue #13007: whichdb should recognize gdbm 1.9 magic numbers.
+
+- Issue #9173: Let shutil._make_archive work if the logger argument is None.
+
+- Issue #12650: Fix a race condition where a subprocess.Popen could leak
+ resources (FD/zombie) when killed at the wrong time.
+
+- Issue #12752: Fix regression which prevented locale.normalize() from
+ accepting unicode strings.
+
+- Issue #12683: urlparse updated to include svn as schemes that uses relative
+ paths. (svn from 1.5 onwards support relative path).
+
+- Issue #11933: Fix incorrect mtime comparison in distutils.
+
+- Issues #11104, #8688: Fix the behavior of distutils' sdist command with
+ manually-maintained MANIFEST files.
+
+- Issue #8887: "pydoc somebuiltin.somemethod" (or help('somebuiltin.somemethod')
+ in Python code) now finds the doc of the method.
+
+- Issue #12603: Fix pydoc.synopsis() on files with non-negative st_mtime.
+
+- Issue #12514: Use try/finally to assure the timeit module restores garbage
+ collections when it is done.
+
+- Issue #12607: In subprocess, fix issue where if stdin, stdout or stderr is
+ given as a low fd, it gets overwritten.
+
+- Issue #12102: Document that buffered files must be flushed before being used
+ with mmap. Patch by Steffen Daode Nurpmeso.
+
+- Issue #12560: Build libpython.so on OpenBSD. Patch by Stefan Sperling.
+
+- Issue #1813: Fix codec lookup and setting/getting locales under Turkish
+ locales.
+
+- Issue #10883: Fix socket leaks in urllib when using FTP.
+
+- Issue #12592: Make Python build on OpenBSD 5 (and future major releases).
+
+- Issue #12372: POSIX semaphores are broken on AIX: don't use them.
+
+- Issue #12571: Add a plat-linux3 directory mirroring the plat-linux2
+ directory, so that "import DLFCN" and other similar imports work on
+ Linux 3.0.
+
+- Issue #7484: smtplib no longer puts <> around addresses in VRFY and EXPN
+ commands; they aren't required and in fact postfix doesn't support that form.
+
+- Issue #11603: Fix a crash when __str__ is rebound as __repr__. Patch by
+ Andreas Stührk.
+
+- Issue #12502: asyncore: fix polling loop with AF_UNIX sockets.
+
+- Issue #4376: ctypes now supports nested structures in a endian different than
+ the parent structure. Patch by Vlad Riscutia.
+
+- Issue #12493: subprocess: Popen.communicate() now also handles EINTR errors
+ if the process has only one pipe.
+
+- Issue #12467: warnings: fix a race condition if a warning is emitted at
+ shutdown, if globals()['__file__'] is None.
+
+- Issue #12352: Fix a deadlock in multiprocessing.Heap when a block is freed by
+ the garbage collector while the Heap lock is held.
+
+- Issue #9516: On Mac OS X, change Distutils to no longer globally attempt to
+ check or set the MACOSX_DEPLOYMENT_TARGET environment variable for the
+ interpreter process. This could cause failures in non-Distutils subprocesses
+ and was unreliable since tests or user programs could modify the interpreter
+ environment after Distutils set it. Instead, have Distutils set the the
+ deployment target only in the environment of each build subprocess. It is
+ still possible to globally override the default by setting
+ MACOSX_DEPLOYMENT_TARGET before launching the interpreter; its value must be
+ greater or equal to the default value, the value with which the interpreter
+ was built.
+
+- Issue #11802: The cache in filecmp now has a maximum size of 100 so that
+ it won't grow without bound.
+
+- Issue #12404: Remove C89 incompatible code from mmap module. Patch by Akira
+ Kitada.
+
+- Issue #11700: mailbox proxy object close methods can now be called multiple
+ times without error, and _ProxyFile now closes the wrapped file.
+
+- Issue #12133: AbstractHTTPHandler.do_open() of urllib.request closes the HTTP
+ connection if its getresponse() method fails with a socket error. Patch
+ written by Ezio Melotti.
+
+- Issue #9284: Allow inspect.findsource() to find the source of doctest
+ functions.
+
+- Issue #10694: zipfile now ignores garbage at the end of a zipfile.
+
+- Issue #11583: Speed up os.path.isdir on Windows by using GetFileAttributes
+ instead of os.stat.
+
+- Issue #12080: Fix a performance issue in Decimal._power_exact that caused
+ some corner-case Decimal.__pow__ calls to take an unreasonably long time.
+
+- Named tuples now work correctly with vars().
+
+- sys.setcheckinterval() now updates the current ticker count as well as
+ updating the check interval, so if the user decreases the check interval,
+ the ticker doesn't have to wind down to zero from the old starting point
+ before the new interval takes effect. And if the user increases the
+ interval, it makes sure the new limit takes effect right away rather have an
+ early task switch before recognizing the new interval.
+
+- Issue #12085: Fix an attribute error in subprocess.Popen destructor if the
+ constructor has failed, e.g. because of an undeclared keyword argument. Patch
+ written by Oleg Oshmyan.
+
+Extension Modules
+-----------------
+
+- Issue #13070: Fix a crash when a TextIOWrapper caught in a reference cycle
+ would be finalized after the reference to its underlying BufferedRWPair's
+ writer got cleared by the GC.
+
+- Issue #12881: ctypes: Fix segfault with large structure field names.
+
+- Issue #13013: ctypes: Fix a reference leak in PyCArrayType_from_ctype.
+ Thanks to Suman Saha for finding the bug and providing a patch.
+
+- Issue #13022: Fix: _multiprocessing.recvfd() doesn't check that
+ file descriptor was actually received.
+
+- Issue #12483: ctypes: Fix a crash when the destruction of a callback
+ object triggers the garbage collector.
+
+- Issue #12950: Fix passing file descriptors in multiprocessing, under
+ OpenIndiana/Illumos.
+
+- Issue #12764: Fix a crash in ctypes when the name of a Structure field is not
+ a string.
+
+- Issue #9651: Fix a crash when ctypes.create_string_buffer(0) was passed to
+ some functions like file.write().
+
+- Issue #10309: Define _GNU_SOURCE so that mremap() gets the proper
+ signature. Without this, architectures where sizeof void* != sizeof int are
+ broken. Patch given by Hallvard B Furuseth.
+
+Build
+-----
+
+- Issue #8746: Correct faulty configure checks so that os.chflags() and
+ os.lchflags() are once again built on systems that support these
+ functions (*BSD and OS X). Also add new stat file flags for OS X
+ (UF_HIDDEN and UF_COMPRESSED).
+
+Tools/Demos
+-----------
+
+- Issue #10639: reindent.py no longer converts newlines and will raise
+ an error if attempting to convert a file with mixed newlines.
+
+Tests
+-----
+
+- Issue #12821: Fix test_fcntl failures on OpenBSD 5.
+
+- Issue #12331: The test suite for lib2to3 can now run from an installed
+ Python.
+
+- Issue #12549: Correct test_platform to not fail when OS X returns 'x86_64'
+ as the processor type on some Mac systems.
+
+- Skip network tests when getaddrinfo() returns EAI_AGAIN, meaning a temporary
+ failure in name resolution.
+
+- Avoid failing in test_robotparser when mueblesmoraleda.com is flaky and
+ an overzealous DNS service (e.g. OpenDNS) redirects to a placeholder
+ Web site.
+
+- Avoid failing in test_urllibnet.test_bad_address when some overzealous
+ DNS service (e.g. OpenDNS) resolves a non-existent domain name. The test
+ is now skipped instead.
+
+- Issue #8716: Avoid crashes caused by Aqua Tk on OSX when attempting to run
+ test_tk or test_ttk_guionly under a username that is not currently logged
+ in to the console windowserver (as may be the case under buildbot or ssh).
+
+- Issue #12141: Install a copy of template C module file so that
+ test_build_ext of test_distutils is no longer silently skipped when
+ run outside of a build directory.
+
+- Issue #8746: Add additional tests for os.chflags() and os.lchflags().
+ Patch by Garrett Cooper.
+
+- Issue #10736: Fix test_ttk test_widgets failures with Cocoa Tk 8.5.9
+ on Mac OS X. (Patch by Ronald Oussoren)
+
+- Issue #12057: Add tests for ISO 2022 codecs (iso2022_jp, iso2022_jp_2,
+ iso2022_kr).
+
+
+What's New in Python 2.7.2?
+===========================
+
+*Release date: 2011-06-11*
+
+Library
+-------
+
+- Issue #12009: Fixed regression in netrc file comment handling.
+
+Extension Modules
+-----------------
+
+- Issue #1221: Make pyexpat.__version__ equal to the Python version.
+
+
+What's New in Python 2.7.2 release candidate 1?
+===============================================
+
+*Release date: 2011-05-29*
+
+Core and Builtins
+-----------------
+
+- Issue #9670: Increase the default stack size for secondary threads on
+ Mac OS X and FreeBSD to reduce the chances of a crash instead of a
+ "maximum recursion depth" RuntimeError exception.
+ (patch by Ronald Oussoren)
+
+- Correct lookup of __dir__ on objects. This allows old-style classes to have
+ __dir__. It also causes errors besides AttributeError found on lookup to be
+ propagated.
+
+- Issue #1195: Fix input() if it is interrupted by CTRL+d and then CTRL+c,
+ clear the end-of-file indicator after CTRL+d.
+
+- Issue #8651: PyArg_Parse*() functions raise an OverflowError if the file
+ doesn't have PY_SSIZE_T_CLEAN define and the size doesn't fit in an int
+ (length bigger than 2^31-1 bytes).
+
+- Issue #8651: Fix "z#" format of PyArg_Parse*() function: the size was not
+ written if PY_SSIZE_T_CLEAN is defined.
+
+- Issue #9756: When calling a method descriptor or a slot wrapper descriptor,
+ the check of the object type doesn't read the __class__ attribute anymore.
+ Fix a crash if a class override its __class__ attribute (e.g. a proxy of the
+ str type). Patch written by Andreas Stührk.
+
+- Issue #10517: After fork(), reinitialize the TLS used by the PyGILState_*
+ APIs, to avoid a crash with the pthread implementation in RHEL 5. Patch
+ by Charles-François Natali.
+
- Issue #6780: fix starts/endswith error message to mention that tuples are
accepted too.
@@ -61,6 +412,73 @@
Library
-------
+- Issue #12590: IDLE editor window now always displays the first line
+ when opening a long file. With Tk 8.5, the first line was hidden.
+
+- Issue #12161: Cause StringIO.getvalue() to raise a ValueError when used on a
+ closed StringIO instance.
+
+- Issue #12182: Fix pydoc.HTMLDoc.multicolumn() if Python uses the new (true)
+ division (python -Qnew). Patch written by Ralf W. Grosse-Kunstleve.
+
+- Issue #12175: RawIOBase.readall() now returns None if read() returns None.
+
+- Issue #12175: FileIO.readall() now raises a ValueError instead of an IOError
+ if the file is closed.
+
+- Issue #1441530: In imaplib, use makefile() to wrap the SSL socket to avoid
+ heap fragmentation and MemoryError with some malloc implementations.
+
+- Issue #12100: Don't reset incremental encoders of CJK codecs at each call to
+ their encode() method anymore, but continue to call the reset() method if the
+ final argument is True.
+
+- Issue #12124: zipimport doesn't keep a reference to zlib.decompress() anymore
+ to be able to unload the module.
+
+- Issue #11088: don't crash when using F5 to run a script in IDLE on MacOSX
+ with Tk 8.5.
+
+- Issue #10154, #10090: change the normalization of UTF-8 to "UTF-8" instead
+ of "UTF8" in the locale module as the latter is not supported MacOSX and OpenBSD.
+
+- Issue #9516: avoid errors in sysconfig when MACOSX_DEPLOYMENT_TARGET is
+ set in shell.
+
+- Issue #12050: zlib.decompressobj().decompress() now clears the unconsumed_tail
+ attribute when called without a max_length argument.
+
+- Issue #12062: In the `io` module, fix a flushing bug when doing a certain
+ type of I/O sequence on a file opened in read+write mode (namely: reading,
+ seeking a bit forward, writing, then seeking before the previous write but
+ still within buffered data, and writing again).
+
+- Issue #8498: In socket.accept(), allow to specify 0 as a backlog value in
+ order to accept exactly one connection. Patch by Daniel Evers.
+
+- Issue #12012: ssl.PROTOCOL_SSLv2 becomes optional.
+
+- Issue #11164: Remove obsolete allnodes test from minidom test.
+
+- Issue #11927: SMTP_SSL now uses port 465 by default as documented. Patch
+ by Kasun Herath.
+
+- Issue 11999: fixed sporadic sync failure mailbox.Maildir due to its trying to
+ detect mtime changes by comparing to the system clock instead of to the
+ previous value of the mtime.
+
+- Issue #10684: shutil.move used to delete a folder on case insensitive
+ filesystems when the source and destination name where the same except
+ for the case.
+
+- Issue #11982: fix json.loads('""') to return u'' rather than ''.
+
+- Issue #11277: mmap.mmap() calls fcntl(fd, F_FULLFSYNC) on Mac OS X to get
+ around a mmap bug with sparse files. Patch written by Steffen Daode Nurpmeso.
+
+- Issue #10761: Fix tarfile.extractall failure when symlinked files are
+ present. Initial patch by Scott Leerssen.
+
- Issue #11763: don't use difflib in TestCase.assertMultiLineEqual if the
strings are too long.
@@ -326,6 +744,18 @@
Extension Modules
-----------------
+- Stop using the old interface for providing methods and attributes in the _sre
+ module. Among other things, this gives these classes ``__class__``
+ attributes. (See #12099)
+
+- Issue #10169: Fix argument parsing in socket.sendto() to avoid error masking.
+
+- Issue #12051: Fix segfault in json.dumps() while encoding highly-nested
+ objects using the C accelerations.
+
+- Issue #12017: Fix segfault in json.loads() while decoding highly-nested
+ objects using the C accelerations.
+
- Issue #1838: Prevent segfault in ctypes, when _as_parameter_ on a class is set
to an instance of the class.
@@ -334,6 +764,10 @@
Build
-----
+- Issue #11217: For 64-bit/32-bit Mac OS X universal framework builds,
+ ensure "make install" creates symlinks in --prefix bin for the "-32"
+ files in the framework bin directory like the installer does.
+
- Issue #11411: Fix 'make DESTDIR=' with a relative destination.
- Issue #10709: Add updated AIX notes in Misc/README.AIX.
@@ -381,6 +815,12 @@
Tests
-----
+- Issue #12205: Fix test_subprocess failure due to uninstalled test data.
+
+- Issue #5723: Improve json tests to be executed with and without accelerations.
+
+- Issue #11910: Fix test_heapq to skip the C tests when _heapq is missing.
+
- Fix test_startfile to wait for child process to terminate before finishing.
- Issue #11719: Fix message about unexpected test_msilib skip on non-Windows
diff --git a/Misc/RPM/python-2.7.spec b/Misc/RPM/python-2.7.spec
index dc437dd..d095465 100644
--- a/Misc/RPM/python-2.7.spec
+++ b/Misc/RPM/python-2.7.spec
@@ -39,7 +39,7 @@
%define name python
#--start constants--
-%define version 2.7.1
+%define version 2.7.2
%define libvers 2.7
#--end constants--
%define release 1pydotorg
diff --git a/Misc/python.man b/Misc/python.man
index ddfccef..9308787 100644
--- a/Misc/python.man
+++ b/Misc/python.man
@@ -31,7 +31,7 @@
.B \-O
]
[
-.B \-O0
+.B \-OO
]
[
.B -Q
@@ -148,7 +148,7 @@
.I .pyc
to \fI.pyo\fP. Given twice, causes docstrings to be discarded.
.TP
-.B \-O0
+.B \-OO
Discard docstrings in addition to the \fB-O\fP optimizations.
.TP
.BI "\-Q " argument
diff --git a/Modules/_bsddb.c b/Modules/_bsddb.c
index d2d12ff..d99df4b 100644
--- a/Modules/_bsddb.c
+++ b/Modules/_bsddb.c
@@ -8795,7 +8795,7 @@
{"txn_recover", (PyCFunction)DBEnv_txn_recover, METH_NOARGS},
#if (DBVER < 48)
{"set_rpc_server", (PyCFunction)DBEnv_set_rpc_server,
- METH_VARARGS||METH_KEYWORDS},
+ METH_VARARGS|METH_KEYWORDS},
#endif
#if (DBVER >= 43)
{"set_mp_max_openfd", (PyCFunction)DBEnv_set_mp_max_openfd, METH_VARARGS},
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index c6c6dbd..4ae2c41 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -2576,8 +2576,10 @@
view->ndim = dict->ndim;
view->shape = dict->shape;
view->itemsize = self->b_size;
- for (i = 0; i < view->ndim; ++i) {
- view->itemsize /= dict->shape[i];
+ if (view->itemsize) {
+ for (i = 0; i < view->ndim; ++i) {
+ view->itemsize /= dict->shape[i];
+ }
}
view->strides = NULL;
view->suboffsets = NULL;
@@ -4676,6 +4678,7 @@
if (!PyType_Check(itemtype)) {
PyErr_SetString(PyExc_TypeError,
"Expected a type object");
+ Py_DECREF(key);
return NULL;
}
#ifdef MS_WIN64
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index 2b54a85..47dbe05 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -18,6 +18,7 @@
CThunkObject_dealloc(PyObject *_self)
{
CThunkObject *self = (CThunkObject *)_self;
+ PyObject_GC_UnTrack(self);
Py_XDECREF(self->converters);
Py_XDECREF(self->callable);
Py_XDECREF(self->restype);
diff --git a/Modules/_ctypes/libffi/src/dlmalloc.c b/Modules/_ctypes/libffi/src/dlmalloc.c
index 783c5c2..582ddc3 100644
--- a/Modules/_ctypes/libffi/src/dlmalloc.c
+++ b/Modules/_ctypes/libffi/src/dlmalloc.c
@@ -457,6 +457,11 @@
#define LACKS_ERRNO_H
#define MALLOC_FAILURE_ACTION
#define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */
+#elif !defined _GNU_SOURCE
+/* mremap() on Linux requires this via sys/mman.h
+ * See roundup issue 10309
+ */
+#define _GNU_SOURCE 1
#endif /* WIN32 */
#if defined(DARWIN) || defined(_DARWIN)
diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c
index 4e7ea12..773233f 100644
--- a/Modules/_ctypes/stgdict.c
+++ b/Modules/_ctypes/stgdict.c
@@ -494,14 +494,33 @@
char *fieldfmt = dict->format ? dict->format : "B";
char *fieldname = PyString_AsString(name);
char *ptr;
- Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
- char *buf = alloca(len + 2 + 1);
+ Py_ssize_t len;
+ char *buf;
+ if (fieldname == NULL)
+ {
+ PyErr_Format(PyExc_TypeError,
+ "structure field name must be string not %s",
+ name->ob_type->tp_name);
+
+ Py_DECREF(pair);
+ return -1;
+ }
+
+ len = strlen(fieldname) + strlen(fieldfmt);
+
+ buf = PyMem_Malloc(len + 2 + 1);
+ if (buf == NULL) {
+ Py_DECREF(pair);
+ PyErr_NoMemory();
+ return -1;
+ }
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
PyMem_Free(ptr);
+ PyMem_Free(buf);
if (stgdict->format == NULL) {
Py_DECREF(pair);
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index 5816a93..1b81647 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -721,6 +721,28 @@
*/
static PyObject *
+buffered_flush_and_rewind_unlocked(buffered *self)
+{
+ PyObject *res;
+
+ res = _bufferedwriter_flush_unlocked(self, 0);
+ if (res == NULL)
+ return NULL;
+ Py_DECREF(res);
+
+ if (self->readable) {
+ /* Rewind the raw stream so that its position corresponds to
+ the current logical position. */
+ Py_off_t n;
+ n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
+ _bufferedreader_reset_buf(self);
+ if (n == -1)
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+static PyObject *
buffered_flush(buffered *self, PyObject *args)
{
PyObject *res;
@@ -730,16 +752,7 @@
if (!ENTER_BUFFERED(self))
return NULL;
- res = _bufferedwriter_flush_unlocked(self, 0);
- if (res != NULL && self->readable) {
- /* Rewind the raw stream so that its position corresponds to
- the current logical position. */
- Py_off_t n;
- n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
- if (n == -1)
- Py_CLEAR(res);
- _bufferedreader_reset_buf(self);
- }
+ res = buffered_flush_and_rewind_unlocked(self);
LEAVE_BUFFERED(self)
return res;
@@ -760,7 +773,7 @@
return NULL;
if (self->writable) {
- res = _bufferedwriter_flush_unlocked(self, 1);
+ res = buffered_flush_and_rewind_unlocked(self);
if (res == NULL)
goto end;
Py_CLEAR(res);
@@ -795,19 +808,18 @@
if (!ENTER_BUFFERED(self))
return NULL;
res = _bufferedreader_read_all(self);
- LEAVE_BUFFERED(self)
}
else {
res = _bufferedreader_read_fast(self, n);
- if (res == Py_None) {
- Py_DECREF(res);
- if (!ENTER_BUFFERED(self))
- return NULL;
- res = _bufferedreader_read_generic(self, n);
- LEAVE_BUFFERED(self)
- }
+ if (res != Py_None)
+ return res;
+ Py_DECREF(res);
+ if (!ENTER_BUFFERED(self))
+ return NULL;
+ res = _bufferedreader_read_generic(self, n);
}
+ LEAVE_BUFFERED(self)
return res;
}
@@ -833,13 +845,6 @@
if (!ENTER_BUFFERED(self))
return NULL;
- if (self->writable) {
- res = _bufferedwriter_flush_unlocked(self, 1);
- if (res == NULL)
- goto end;
- Py_CLEAR(res);
- }
-
/* Return up to n bytes. If at least one byte is buffered, we
only return buffered bytes. Otherwise, we do one raw read. */
@@ -859,6 +864,13 @@
goto end;
}
+ if (self->writable) {
+ res = buffered_flush_and_rewind_unlocked(self);
+ if (res == NULL)
+ goto end;
+ Py_DECREF(res);
+ }
+
/* Fill the buffer from the raw stream, and copy it to the result. */
_bufferedreader_reset_buf(self);
r = _bufferedreader_fill_buffer(self);
@@ -881,24 +893,10 @@
static PyObject *
buffered_readinto(buffered *self, PyObject *args)
{
- PyObject *res = NULL;
-
CHECK_INITIALIZED(self)
- /* TODO: use raw.readinto() instead! */
- if (self->writable) {
- if (!ENTER_BUFFERED(self))
- return NULL;
- res = _bufferedwriter_flush_unlocked(self, 0);
- LEAVE_BUFFERED(self)
- if (res == NULL)
- goto end;
- Py_DECREF(res);
- }
- res = bufferediobase_readinto((PyObject *)self, args);
-
-end:
- return res;
+ /* TODO: use raw.readinto() (or a direct copy from our buffer) instead! */
+ return bufferediobase_readinto((PyObject *)self, args);
}
static PyObject *
@@ -936,12 +934,6 @@
goto end_unlocked;
/* Now we try to get some more from the raw stream */
- if (self->writable) {
- res = _bufferedwriter_flush_unlocked(self, 1);
- if (res == NULL)
- goto end;
- Py_CLEAR(res);
- }
chunks = PyList_New(0);
if (chunks == NULL)
goto end;
@@ -955,9 +947,16 @@
}
Py_CLEAR(res);
written += n;
+ self->pos += n;
if (limit >= 0)
limit -= n;
}
+ if (self->writable) {
+ PyObject *r = buffered_flush_and_rewind_unlocked(self);
+ if (r == NULL)
+ goto end;
+ Py_DECREF(r);
+ }
for (;;) {
_bufferedreader_reset_buf(self);
@@ -1126,20 +1125,11 @@
return NULL;
if (self->writable) {
- res = _bufferedwriter_flush_unlocked(self, 0);
+ res = buffered_flush_and_rewind_unlocked(self);
if (res == NULL)
goto end;
Py_CLEAR(res);
}
- if (self->readable) {
- if (pos == Py_None) {
- /* Rewind the raw stream so that its position corresponds to
- the current logical position. */
- if (_buffered_raw_seek(self, -RAW_OFFSET(self), 1) == -1)
- goto end;
- }
- _bufferedreader_reset_buf(self);
- }
res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_truncate, pos, NULL);
if (res == NULL)
goto end;
@@ -1341,17 +1331,18 @@
Py_DECREF(chunks);
return NULL;
}
+ self->pos += current_size;
}
- _bufferedreader_reset_buf(self);
/* We're going past the buffer's bounds, flush it */
if (self->writable) {
- res = _bufferedwriter_flush_unlocked(self, 1);
+ res = buffered_flush_and_rewind_unlocked(self);
if (res == NULL) {
Py_DECREF(chunks);
return NULL;
}
Py_CLEAR(res);
}
+ _bufferedreader_reset_buf(self);
while (1) {
if (data) {
if (PyList_Append(chunks, data) < 0) {
@@ -1434,6 +1425,14 @@
memcpy(out, self->buffer + self->pos, current_size);
remaining -= current_size;
written += current_size;
+ self->pos += current_size;
+ }
+ /* Flush the write buffer if necessary */
+ if (self->writable) {
+ PyObject *r = buffered_flush_and_rewind_unlocked(self);
+ if (r == NULL)
+ goto error;
+ Py_DECREF(r);
}
_bufferedreader_reset_buf(self);
while (remaining > 0) {
@@ -1810,7 +1809,7 @@
avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t);
if (buf.len <= avail) {
memcpy(self->buffer + self->pos, buf.buf, buf.len);
- if (!VALID_WRITE_BUFFER(self)) {
+ if (!VALID_WRITE_BUFFER(self) || self->write_pos > self->pos) {
self->write_pos = self->pos;
}
ADJUST_POSITION(self, self->pos + buf.len);
@@ -2180,6 +2179,11 @@
static PyObject *
bufferedrwpair_closed_get(rwpair *self, void *context)
{
+ if (self->writer == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "the BufferedRWPair object is being garbage-collected");
+ return NULL;
+ }
return PyObject_GetAttr((PyObject *) self->writer, _PyIO_str_closed);
}
diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c
index 83921ea..9f90448 100644
--- a/Modules/_io/fileio.c
+++ b/Modules/_io/fileio.c
@@ -474,7 +474,7 @@
fileio_readinto(fileio *self, PyObject *args)
{
Py_buffer pbuf;
- Py_ssize_t n;
+ Py_ssize_t n, len;
if (self->fd < 0)
return err_closed();
@@ -485,9 +485,16 @@
return NULL;
if (_PyVerify_fd(self->fd)) {
+ len = pbuf.len;
Py_BEGIN_ALLOW_THREADS
errno = 0;
- n = read(self->fd, pbuf.buf, pbuf.len);
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ if (len > INT_MAX)
+ len = INT_MAX;
+ n = read(self->fd, pbuf.buf, (int)len);
+#else
+ n = read(self->fd, pbuf.buf, len);
+#endif
Py_END_ALLOW_THREADS
} else
n = -1;
@@ -539,6 +546,8 @@
Py_ssize_t total = 0;
int n;
+ if (self->fd < 0)
+ return err_closed();
if (!_PyVerify_fd(self->fd))
return PyErr_SetFromErrno(PyExc_IOError);
@@ -618,6 +627,10 @@
return fileio_readall(self);
}
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ if (size > INT_MAX)
+ size = INT_MAX;
+#endif
bytes = PyBytes_FromStringAndSize(NULL, size);
if (bytes == NULL)
return NULL;
@@ -626,7 +639,11 @@
if (_PyVerify_fd(self->fd)) {
Py_BEGIN_ALLOW_THREADS
errno = 0;
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ n = read(self->fd, ptr, (int)size);
+#else
n = read(self->fd, ptr, size);
+#endif
Py_END_ALLOW_THREADS
} else
n = -1;
@@ -653,7 +670,7 @@
fileio_write(fileio *self, PyObject *args)
{
Py_buffer pbuf;
- Py_ssize_t n;
+ Py_ssize_t n, len;
if (self->fd < 0)
return err_closed();
@@ -666,7 +683,14 @@
if (_PyVerify_fd(self->fd)) {
Py_BEGIN_ALLOW_THREADS
errno = 0;
- n = write(self->fd, pbuf.buf, pbuf.len);
+ len = pbuf.len;
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ if (len > INT_MAX)
+ len = INT_MAX;
+ n = write(self->fd, pbuf.buf, (int)len);
+#else
+ n = write(self->fd, pbuf.buf, len);
+#endif
Py_END_ALLOW_THREADS
} else
n = -1;
diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c
index e129ca9..176761d 100644
--- a/Modules/_io/iobase.c
+++ b/Modules/_io/iobase.c
@@ -814,6 +814,14 @@
Py_DECREF(chunks);
return NULL;
}
+ if (data == Py_None) {
+ if (PyList_GET_SIZE(chunks) == 0) {
+ Py_DECREF(chunks);
+ return data;
+ }
+ Py_DECREF(data);
+ break;
+ }
if (!PyBytes_Check(data)) {
Py_DECREF(chunks);
Py_DECREF(data);
diff --git a/Modules/_io/stringio.c b/Modules/_io/stringio.c
index cf0f8b1..e3de751 100644
--- a/Modules/_io/stringio.c
+++ b/Modules/_io/stringio.c
@@ -464,7 +464,7 @@
CHECK_INITIALIZED(self);
if (!PyUnicode_Check(obj)) {
- PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'",
+ PyErr_Format(PyExc_TypeError, "unicode argument expected, got '%s'",
Py_TYPE(obj)->tp_name);
return NULL;
}
diff --git a/Modules/_json.c b/Modules/_json.c
index 71d3e58..6b321e5 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -380,24 +380,6 @@
}
static PyObject *
-join_list_string(PyObject *lst)
-{
- /* return ''.join(lst) */
- static PyObject *joinfn = NULL;
- if (joinfn == NULL) {
- PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
- if (ustr == NULL)
- return NULL;
-
- joinfn = PyObject_GetAttrString(ustr, "join");
- Py_DECREF(ustr);
- if (joinfn == NULL)
- return NULL;
- }
- return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
-}
-
-static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
@@ -595,7 +577,7 @@
Py_DECREF(chunk);
}
- rval = join_list_string(chunks);
+ rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
@@ -1506,6 +1488,7 @@
Returns a new PyObject representation of the term.
*/
+ PyObject *res;
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
if (idx >= length) {
@@ -1521,10 +1504,20 @@
next_idx_ptr);
case '{':
/* object */
- return _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
+ if (Py_EnterRecursiveCall(" while decoding a JSON object "
+ "from a byte string"))
+ return NULL;
+ res = _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
+ Py_LeaveRecursiveCall();
+ return res;
case '[':
/* array */
- return _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
+ if (Py_EnterRecursiveCall(" while decoding a JSON array "
+ "from a byte string"))
+ return NULL;
+ res = _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
+ Py_LeaveRecursiveCall();
+ return res;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
@@ -1582,6 +1575,7 @@
Returns a new PyObject representation of the term.
*/
+ PyObject *res;
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
if (idx >= length) {
@@ -1596,10 +1590,20 @@
next_idx_ptr);
case '{':
/* object */
- return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
+ if (Py_EnterRecursiveCall(" while decoding a JSON object "
+ "from a unicode string"))
+ return NULL;
+ res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
+ Py_LeaveRecursiveCall();
+ return res;
case '[':
/* array */
- return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
+ if (Py_EnterRecursiveCall(" while decoding a JSON array "
+ "from a unicode string"))
+ return NULL;
+ res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
+ Py_LeaveRecursiveCall();
+ return res;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
@@ -1995,10 +1999,18 @@
return _steal_list_append(rval, encoded);
}
else if (PyList_Check(obj) || PyTuple_Check(obj)) {
- return encoder_listencode_list(s, rval, obj, indent_level);
+ if (Py_EnterRecursiveCall(" while encoding a JSON object"))
+ return -1;
+ rv = encoder_listencode_list(s, rval, obj, indent_level);
+ Py_LeaveRecursiveCall();
+ return rv;
}
else if (PyDict_Check(obj)) {
- return encoder_listencode_dict(s, rval, obj, indent_level);
+ if (Py_EnterRecursiveCall(" while encoding a JSON object"))
+ return -1;
+ rv = encoder_listencode_dict(s, rval, obj, indent_level);
+ Py_LeaveRecursiveCall();
+ return rv;
}
else {
PyObject *ident = NULL;
@@ -2024,7 +2036,12 @@
Py_XDECREF(ident);
return -1;
}
+
+ if (Py_EnterRecursiveCall(" while encoding a JSON object"))
+ return -1;
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
+ Py_LeaveRecursiveCall();
+
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
diff --git a/Modules/_multiprocessing/multiprocessing.c b/Modules/_multiprocessing/multiprocessing.c
index 93f1c48..31a8da8 100644
--- a/Modules/_multiprocessing/multiprocessing.c
+++ b/Modules/_multiprocessing/multiprocessing.c
@@ -97,32 +97,38 @@
/* Functions for transferring file descriptors between processes.
Reimplements some of the functionality of the fdcred
module at http://www.mca-ltd.com/resources/fdcred_1.tgz. */
+/* Based in http://resin.csoft.net/cgi-bin/man.cgi?section=3&topic=CMSG_DATA */
static PyObject *
multiprocessing_sendfd(PyObject *self, PyObject *args)
{
int conn, fd, res;
- char dummy_char;
- char buf[CMSG_SPACE(sizeof(int))];
- struct msghdr msg = {0};
struct iovec dummy_iov;
+ char dummy_char;
+ struct msghdr msg;
struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr hdr;
+ unsigned char buf[CMSG_SPACE(sizeof(int))];
+ } cmsgbuf;
if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
- msg.msg_control = buf;
- msg.msg_controllen = sizeof(buf);
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = &cmsgbuf.buf;
+ msg.msg_controllen = sizeof(cmsgbuf.buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
+
cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- msg.msg_controllen = cmsg->cmsg_len;
- *CMSG_DATA(cmsg) = fd;
+ * (int *) CMSG_DATA(cmsg) = fd;
Py_BEGIN_ALLOW_THREADS
res = sendmsg(conn, &msg, 0);
@@ -138,20 +144,26 @@
{
int conn, fd, res;
char dummy_char;
- char buf[CMSG_SPACE(sizeof(int))];
- struct msghdr msg = {0};
struct iovec dummy_iov;
+ struct msghdr msg = {0};
struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr hdr;
+ unsigned char buf[CMSG_SPACE(sizeof(int))];
+ } cmsgbuf;
if (!PyArg_ParseTuple(args, "i", &conn))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
- msg.msg_control = buf;
- msg.msg_controllen = sizeof(buf);
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = &cmsgbuf.buf;
+ msg.msg_controllen = sizeof(cmsgbuf.buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
+
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
@@ -165,7 +177,18 @@
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
- fd = *CMSG_DATA(cmsg);
+ if (msg.msg_controllen < CMSG_LEN(sizeof(int)) ||
+ (cmsg = CMSG_FIRSTHDR(&msg)) == NULL ||
+ cmsg->cmsg_level != SOL_SOCKET ||
+ cmsg->cmsg_type != SCM_RIGHTS ||
+ cmsg->cmsg_len < CMSG_LEN(sizeof(int))) {
+ /* If at least one control message is present, there should be
+ no room for any further data in the buffer. */
+ PyErr_SetString(PyExc_RuntimeError, "No file descriptor received");
+ return NULL;
+ }
+
+ fd = * (int *) CMSG_DATA(cmsg);
return Py_BuildValue("i", fd);
}
diff --git a/Modules/_sqlite/cursor.c b/Modules/_sqlite/cursor.c
index 26e3307..94c3f40 100644
--- a/Modules/_sqlite/cursor.c
+++ b/Modules/_sqlite/cursor.c
@@ -55,8 +55,8 @@
dst = buf;
*dst = 0;
- while (isalpha(*src) && dst - buf < sizeof(buf) - 2) {
- *dst++ = tolower(*src++);
+ while (Py_ISALPHA(*src) && dst - buf < sizeof(buf) - 2) {
+ *dst++ = Py_TOLOWER(*src++);
}
*dst = 0;
diff --git a/Modules/_sre.c b/Modules/_sre.c
index 9315f10..200e8dd 100644
--- a/Modules/_sre.c
+++ b/Modules/_sre.c
@@ -2598,46 +2598,22 @@
{NULL, NULL}
};
-static PyObject*
-pattern_getattr(PatternObject* self, char* name)
-{
- PyObject* res;
-
- res = Py_FindMethod(pattern_methods, (PyObject*) self, name);
-
- if (res)
- return res;
-
- PyErr_Clear();
-
- /* attributes */
- if (!strcmp(name, "pattern")) {
- Py_INCREF(self->pattern);
- return self->pattern;
- }
-
- if (!strcmp(name, "flags"))
- return Py_BuildValue("i", self->flags);
-
- if (!strcmp(name, "groups"))
- return Py_BuildValue("i", self->groups);
-
- if (!strcmp(name, "groupindex") && self->groupindex) {
- Py_INCREF(self->groupindex);
- return self->groupindex;
- }
-
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
-}
+#define PAT_OFF(x) offsetof(PatternObject, x)
+static PyMemberDef pattern_members[] = {
+ {"pattern", T_OBJECT, PAT_OFF(pattern), READONLY},
+ {"flags", T_INT, PAT_OFF(flags), READONLY},
+ {"groups", T_PYSSIZET, PAT_OFF(groups), READONLY},
+ {"groupindex", T_OBJECT, PAT_OFF(groupindex), READONLY},
+ {NULL} /* Sentinel */
+};
statichere PyTypeObject Pattern_Type = {
PyObject_HEAD_INIT(NULL)
0, "_" SRE_MODULE ".SRE_Pattern",
sizeof(PatternObject), sizeof(SRE_CODE),
(destructor)pattern_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)pattern_getattr, /*tp_getattr*/
+ 0, /* tp_print */
+ 0, /* tp_getattrn */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
@@ -2650,12 +2626,16 @@
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
- Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
pattern_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(PatternObject, weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ pattern_methods, /* tp_methods */
+ pattern_members, /* tp_members */
};
static int _validate(PatternObject *self); /* Forward */
@@ -3562,7 +3542,7 @@
#endif
}
-static PyMethodDef match_methods[] = {
+static struct PyMethodDef match_methods[] = {
{"group", (PyCFunction) match_group, METH_VARARGS},
{"start", (PyCFunction) match_start, METH_VARARGS},
{"end", (PyCFunction) match_end, METH_VARARGS},
@@ -3575,80 +3555,90 @@
{NULL, NULL}
};
-static PyObject*
-match_getattr(MatchObject* self, char* name)
+static PyObject *
+match_lastindex_get(MatchObject *self)
{
- PyObject* res;
-
- res = Py_FindMethod(match_methods, (PyObject*) self, name);
- if (res)
- return res;
-
- PyErr_Clear();
-
- if (!strcmp(name, "lastindex")) {
- if (self->lastindex >= 0)
- return Py_BuildValue("i", self->lastindex);
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- if (!strcmp(name, "lastgroup")) {
- if (self->pattern->indexgroup && self->lastindex >= 0) {
- PyObject* result = PySequence_GetItem(
- self->pattern->indexgroup, self->lastindex
- );
- if (result)
- return result;
- PyErr_Clear();
- }
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- if (!strcmp(name, "string")) {
- if (self->string) {
- Py_INCREF(self->string);
- return self->string;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
- }
-
- if (!strcmp(name, "regs")) {
- if (self->regs) {
- Py_INCREF(self->regs);
- return self->regs;
- } else
- return match_regs(self);
- }
-
- if (!strcmp(name, "re")) {
- Py_INCREF(self->pattern);
- return (PyObject*) self->pattern;
- }
-
- if (!strcmp(name, "pos"))
- return Py_BuildValue("i", self->pos);
-
- if (!strcmp(name, "endpos"))
- return Py_BuildValue("i", self->endpos);
-
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
+ if (self->lastindex >= 0)
+ return Py_BuildValue("i", self->lastindex);
+ Py_INCREF(Py_None);
+ return Py_None;
}
+static PyObject *
+match_lastgroup_get(MatchObject *self)
+{
+ if (self->pattern->indexgroup && self->lastindex >= 0) {
+ PyObject* result = PySequence_GetItem(
+ self->pattern->indexgroup, self->lastindex
+ );
+ if (result)
+ return result;
+ PyErr_Clear();
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject *
+match_regs_get(MatchObject *self)
+{
+ if (self->regs) {
+ Py_INCREF(self->regs);
+ return self->regs;
+ } else
+ return match_regs(self);
+}
+
+static PyGetSetDef match_getset[] = {
+ {"lastindex", (getter)match_lastindex_get, (setter)NULL},
+ {"lastgroup", (getter)match_lastgroup_get, (setter)NULL},
+ {"regs", (getter)match_regs_get, (setter)NULL},
+ {NULL}
+};
+
+#define MATCH_OFF(x) offsetof(MatchObject, x)
+static PyMemberDef match_members[] = {
+ {"string", T_OBJECT, MATCH_OFF(string), READONLY},
+ {"re", T_OBJECT, MATCH_OFF(pattern), READONLY},
+ {"pos", T_PYSSIZET, MATCH_OFF(pos), READONLY},
+ {"endpos", T_PYSSIZET, MATCH_OFF(endpos), READONLY},
+ {NULL}
+};
+
+
/* FIXME: implement setattr("string", None) as a special case (to
detach the associated string, if any */
-statichere PyTypeObject Match_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, "_" SRE_MODULE ".SRE_Match",
+static PyTypeObject Match_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_" SRE_MODULE ".SRE_Match",
sizeof(MatchObject), sizeof(Py_ssize_t),
- (destructor)match_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)match_getattr /*tp_getattr*/
+ (destructor)match_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT,
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ match_methods, /* tp_methods */
+ match_members, /* tp_members */
+ match_getset, /* tp_getset */
};
static PyObject*
@@ -3797,34 +3787,42 @@
{NULL, NULL}
};
-static PyObject*
-scanner_getattr(ScannerObject* self, char* name)
-{
- PyObject* res;
-
- res = Py_FindMethod(scanner_methods, (PyObject*) self, name);
- if (res)
- return res;
-
- PyErr_Clear();
-
- /* attributes */
- if (!strcmp(name, "pattern")) {
- Py_INCREF(self->pattern);
- return self->pattern;
- }
-
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
-}
+#define SCAN_OFF(x) offsetof(ScannerObject, x)
+static PyMemberDef scanner_members[] = {
+ {"pattern", T_OBJECT, SCAN_OFF(pattern), READONLY},
+ {NULL} /* Sentinel */
+};
statichere PyTypeObject Scanner_Type = {
PyObject_HEAD_INIT(NULL)
0, "_" SRE_MODULE ".SRE_Scanner",
sizeof(ScannerObject), 0,
(destructor)scanner_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)scanner_getattr, /*tp_getattr*/
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ scanner_methods, /* tp_methods */
+ scanner_members, /* tp_members */
+ 0, /* tp_getset */
};
static PyObject*
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
index 6ed0f4f..dd61660 100644
--- a/Modules/_ssl.c
+++ b/Modules/_ssl.c
@@ -62,8 +62,10 @@
};
enum py_ssl_version {
+#ifndef OPENSSL_NO_SSL2
PY_SSL_VERSION_SSL2,
- PY_SSL_VERSION_SSL3,
+#endif
+ PY_SSL_VERSION_SSL3=1,
PY_SSL_VERSION_SSL23,
PY_SSL_VERSION_TLS1
};
@@ -302,8 +304,10 @@
self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
else if (proto_version == PY_SSL_VERSION_SSL3)
self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
+#ifndef OPENSSL_NO_SSL2
else if (proto_version == PY_SSL_VERSION_SSL2)
self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
+#endif
else if (proto_version == PY_SSL_VERSION_SSL23)
self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
PySSL_END_ALLOW_THREADS
@@ -698,7 +702,7 @@
/* get a memory buffer */
biobuf = BIO_new(BIO_s_mem());
- i = 0;
+ i = -1;
while ((i = X509_get_ext_by_NID(
certificate, NID_subject_alt_name, i)) >= 0) {
@@ -1141,10 +1145,8 @@
#endif
/* Guard against socket too large for select*/
-#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
- if (s->sock_fd >= FD_SETSIZE)
+ if (!_PyIsSelectable_fd(s->sock_fd))
return SOCKET_TOO_LARGE_FOR_SELECT;
-#endif
/* Construct the arguments to select */
tv.tv_sec = (int)s->sock_timeout;
@@ -1708,8 +1710,10 @@
PY_SSL_CERT_REQUIRED);
/* protocol versions */
+#ifndef OPENSSL_NO_SSL2
PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
PY_SSL_VERSION_SSL2);
+#endif
PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
PY_SSL_VERSION_SSL3);
PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index 01d6284..40c8be2 100644
--- a/Modules/_tkinter.c
+++ b/Modules/_tkinter.c
@@ -663,8 +663,8 @@
}
strcpy(argv0, className);
- if (isupper(Py_CHARMASK(argv0[0])))
- argv0[0] = tolower(Py_CHARMASK(argv0[0]));
+ if (Py_ISUPPER(Py_CHARMASK(argv0[0])))
+ argv0[0] = Py_TOLOWER(Py_CHARMASK(argv0[0]));
Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
ckfree(argv0);
diff --git a/Modules/binascii.c b/Modules/binascii.c
index 2d91b7f..8334fe5 100644
--- a/Modules/binascii.c
+++ b/Modules/binascii.c
@@ -1105,8 +1105,8 @@
if (isdigit(c))
return c - '0';
else {
- if (isupper(c))
- c = tolower(c);
+ if (Py_ISUPPER(c))
+ c = Py_TOLOWER(c);
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
}
diff --git a/Modules/cPickle.c b/Modules/cPickle.c
index bd577ad..48b5075 100644
--- a/Modules/cPickle.c
+++ b/Modules/cPickle.c
@@ -2697,11 +2697,6 @@
}
}
- if (PyType_IsSubtype(type, &PyType_Type)) {
- res = save_global(self, args, NULL);
- goto finally;
- }
-
/* Get a reduction callable, and call it. This may come from
* copy_reg.dispatch_table, the object's __reduce_ex__ method,
* or the object's __reduce__ method.
@@ -2717,6 +2712,11 @@
}
}
else {
+ if (PyType_IsSubtype(type, &PyType_Type)) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+
/* Check for a __reduce_ex__ method. */
__reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
if (__reduce__ != NULL) {
diff --git a/Modules/cjkcodecs/_codecs_hk.c b/Modules/cjkcodecs/_codecs_hk.c
index aaf103d..558a42f 100644
--- a/Modules/cjkcodecs/_codecs_hk.c
+++ b/Modules/cjkcodecs/_codecs_hk.c
@@ -115,55 +115,56 @@
REQUIRE_INBUF(2)
- if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
- goto hkscsdec;
-
- TRYMAP_DEC(big5, **outbuf, c, IN2) {
- NEXT(2, 1)
+ if (0xc6 > c || c > 0xc8 || (c < 0xc7 && IN2 < 0xa1)) {
+ TRYMAP_DEC(big5, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ continue;
+ }
}
- else
-hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
- int s = BH2S(c, IN2);
- const unsigned char *hintbase;
- assert(0x87 <= c && c <= 0xfe);
- assert(0x40 <= IN2 && IN2 <= 0xfe);
+ TRYMAP_DEC(big5hkscs, decoded, c, IN2)
+ {
+ int s = BH2S(c, IN2);
+ const unsigned char *hintbase;
- if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
- hintbase = big5hkscs_phint_0;
- s -= BH2S(0x87, 0x40);
- }
- else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
- hintbase = big5hkscs_phint_12130;
- s -= BH2S(0xc6, 0xa1);
- }
- else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
- hintbase = big5hkscs_phint_21924;
- s -= BH2S(0xf9, 0xd6);
- }
- else
- return MBERR_INTERNAL;
+ assert(0x87 <= c && c <= 0xfe);
+ assert(0x40 <= IN2 && IN2 <= 0xfe);
- if (hintbase[s >> 3] & (1 << (s & 7))) {
- WRITEUCS4(decoded | 0x20000)
- NEXT_IN(2)
- }
- else {
- OUT1(decoded)
- NEXT(2, 1)
- }
- }
- else {
- switch ((c << 8) | IN2) {
- case 0x8862: WRITE2(0x00ca, 0x0304); break;
- case 0x8864: WRITE2(0x00ca, 0x030c); break;
- case 0x88a3: WRITE2(0x00ea, 0x0304); break;
- case 0x88a5: WRITE2(0x00ea, 0x030c); break;
- default: return 2;
- }
+ if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
+ hintbase = big5hkscs_phint_0;
+ s -= BH2S(0x87, 0x40);
+ }
+ else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
+ hintbase = big5hkscs_phint_12130;
+ s -= BH2S(0xc6, 0xa1);
+ }
+ else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
+ hintbase = big5hkscs_phint_21924;
+ s -= BH2S(0xf9, 0xd6);
+ }
+ else
+ return MBERR_INTERNAL;
- NEXT(2, 2) /* all decoded codepoints are pairs, above. */
+ if (hintbase[s >> 3] & (1 << (s & 7))) {
+ WRITEUCS4(decoded | 0x20000)
+ NEXT_IN(2)
+ }
+ else {
+ OUT1(decoded)
+ NEXT(2, 1)
+ }
+ continue;
}
+
+ switch ((c << 8) | IN2) {
+ case 0x8862: WRITE2(0x00ca, 0x0304); break;
+ case 0x8864: WRITE2(0x00ca, 0x030c); break;
+ case 0x88a3: WRITE2(0x00ea, 0x0304); break;
+ case 0x88a5: WRITE2(0x00ea, 0x030c); break;
+ default: return 2;
+ }
+
+ NEXT(2, 2) /* all decoded codepoints are pairs, above. */
}
return 0;
diff --git a/Modules/cjkcodecs/_codecs_jp.c b/Modules/cjkcodecs/_codecs_jp.c
index 901d3be..a05e01b 100644
--- a/Modules/cjkcodecs/_codecs_jp.c
+++ b/Modules/cjkcodecs/_codecs_jp.c
@@ -371,11 +371,11 @@
REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
if (c == 0x8e) {
/* JIS X 0201 half-width katakana */
diff --git a/Modules/cjkcodecs/multibytecodec.c b/Modules/cjkcodecs/multibytecodec.c
index 1f31595..14fed3e 100644
--- a/Modules/cjkcodecs/multibytecodec.c
+++ b/Modules/cjkcodecs/multibytecodec.c
@@ -471,7 +471,7 @@
MultibyteEncodeBuffer buf;
Py_ssize_t finalsize, r = 0;
- if (datalen == 0)
+ if (datalen == 0 && !(flags & MBENC_RESET))
return PyString_FromString("");
buf.excobj = NULL;
@@ -506,7 +506,7 @@
break;
}
- if (codec->encreset != NULL)
+ if (codec->encreset != NULL && (flags & MBENC_RESET))
for (;;) {
Py_ssize_t outleft;
@@ -776,8 +776,8 @@
inbuf_end = inbuf + datalen;
r = multibytecodec_encode(ctx->codec, &ctx->state,
- (const Py_UNICODE **)&inbuf,
- datalen, ctx->errors, final ? MBENC_FLUSH : 0);
+ (const Py_UNICODE **)&inbuf, datalen,
+ ctx->errors, final ? MBENC_FLUSH | MBENC_RESET : 0);
if (r == NULL) {
/* recover the original pending buffer */
if (origpending > 0)
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index ff25335..b51ccf9 100644
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -1234,7 +1234,9 @@
return NULL;
lz->cnt++;
oldnext = lz->next;
- lz->next += lz->step;
+ /* The (size_t) cast below avoids the danger of undefined
+ behaviour from signed integer overflow. */
+ lz->next += (size_t)lz->step;
if (lz->next < oldnext || (stop != -1 && lz->next > stop))
lz->next = stop;
return item;
diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c
index e93acda..a5027f5 100644
--- a/Modules/mmapmodule.c
+++ b/Modules/mmapmodule.c
@@ -23,6 +23,9 @@
#ifndef MS_WINDOWS
#define UNIX
+# ifdef __APPLE__
+# include <fcntl.h>
+# endif
#endif
#ifdef MS_WINDOWS
@@ -1170,6 +1173,12 @@
"mmap invalid access parameter.");
}
+#ifdef __APPLE__
+ /* Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific
+ fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug */
+ if (fd != -1)
+ (void)fcntl(fd, F_FULLFSYNC);
+#endif
#ifdef HAVE_FSTAT
# ifdef __VMS
/* on OpenVMS we must ensure that all bytes are written to the file */
@@ -1179,12 +1188,13 @@
# endif
if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
if (map_size == 0) {
+ off_t calc_size;
if (offset >= st.st_size) {
PyErr_SetString(PyExc_ValueError,
"mmap offset is greater than file size");
return NULL;
}
- off_t calc_size = st.st_size - offset;
+ calc_size = st.st_size - offset;
map_size = calc_size;
if (map_size != calc_size) {
PyErr_SetString(PyExc_ValueError,
diff --git a/Modules/ossaudiodev.c b/Modules/ossaudiodev.c
index ebf101a..647a21e 100644
--- a/Modules/ossaudiodev.c
+++ b/Modules/ossaudiodev.c
@@ -129,6 +129,7 @@
}
if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
+ close(fd);
PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename);
return NULL;
}
@@ -425,6 +426,11 @@
if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
return NULL;
+ if (!_PyIsSelectable_fd(self->fd)) {
+ PyErr_SetString(PyExc_ValueError,
+ "file descriptor out of range for select");
+ return NULL;
+ }
/* use select to wait for audio device to be available */
FD_ZERO(&write_set_fds);
FD_SET(self->fd, &write_set_fds);
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
index 48762c1..1040ec5 100644
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -11,8 +11,6 @@
compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used
as the compiler specific macro for the EMX port of gcc to OS/2. */
-/* See also ../Dos/dosmodule.c */
-
#ifdef __APPLE__
/*
* Step 1 of support for weak-linking a number of symbols existing on
@@ -338,20 +336,6 @@
#define USE_TMPNAM_R
#endif
-/* choose the appropriate stat and fstat functions and return structs */
-#undef STAT
-#undef FSTAT
-#undef STRUCT_STAT
-#if defined(MS_WIN64) || defined(MS_WINDOWS)
-# define STAT win32_stat
-# define FSTAT win32_fstat
-# define STRUCT_STAT struct win32_stat
-#else
-# define STAT stat
-# define FSTAT fstat
-# define STRUCT_STAT struct stat
-#endif
-
#if defined(MAJOR_IN_MKDEV)
#include <sys/mkdev.h>
#else
@@ -842,6 +826,20 @@
}
#endif
+/* choose the appropriate stat and fstat functions and return structs */
+#undef STAT
+#undef FSTAT
+#undef STRUCT_STAT
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+# define STAT win32_stat
+# define FSTAT win32_fstat
+# define STRUCT_STAT struct win32_stat
+#else
+# define STAT stat
+# define FSTAT fstat
+# define STRUCT_STAT struct stat
+#endif
+
#ifdef MS_WINDOWS
/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
- time stamps are restricted to second resolution
@@ -3903,7 +3901,7 @@
#endif
gid_t grouplist[MAX_GROUPS];
- /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
+ /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
* This is a helper variable to store the intermediate result when
* that happens.
*
@@ -4199,6 +4197,44 @@
CloseHandle(handle);
return result;
}
+
+PyDoc_STRVAR(posix__isdir__doc__,
+"Return true if the pathname refers to an existing directory.");
+
+static PyObject *
+posix__isdir(PyObject *self, PyObject *args)
+{
+ PyObject *opath;
+ char *path;
+ PyUnicodeObject *po;
+ DWORD attributes;
+
+ if (PyArg_ParseTuple(args, "U|:_isdir", &po)) {
+ Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po);
+
+ attributes = GetFileAttributesW(wpath);
+ if (attributes == INVALID_FILE_ATTRIBUTES)
+ Py_RETURN_FALSE;
+ goto check;
+ }
+ /* Drop the argument parsing error as narrow strings
+ are also valid. */
+ PyErr_Clear();
+
+ if (!PyArg_ParseTuple(args, "et:_isdir",
+ Py_FileSystemDefaultEncoding, &path))
+ return NULL;
+
+ attributes = GetFileAttributesA(path);
+ if (attributes == INVALID_FILE_ATTRIBUTES)
+ Py_RETURN_FALSE;
+
+check:
+ if (attributes & FILE_ATTRIBUTE_DIRECTORY)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
+}
#endif /* MS_WINDOWS */
#ifdef HAVE_PLOCK
@@ -6610,7 +6646,7 @@
{
Py_buffer pbuf;
int fd;
- Py_ssize_t size;
+ Py_ssize_t size, len;
if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf))
return NULL;
@@ -6618,8 +6654,15 @@
PyBuffer_Release(&pbuf);
return posix_error();
}
+ len = pbuf.len;
Py_BEGIN_ALLOW_THREADS
- size = write(fd, pbuf.buf, (size_t)pbuf.len);
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+ if (len > INT_MAX)
+ len = INT_MAX;
+ size = write(fd, pbuf.buf, (int)len);
+#else
+ size = write(fd, pbuf.buf, len);
+#endif
Py_END_ALLOW_THREADS
PyBuffer_Release(&pbuf);
if (size < 0)
@@ -8968,6 +9011,7 @@
{"abort", posix_abort, METH_NOARGS, posix_abort__doc__},
#ifdef MS_WINDOWS
{"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL},
+ {"_isdir", posix__isdir, METH_VARARGS, posix__isdir__doc__},
#endif
#ifdef HAVE_GETLOADAVG
{"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__},
diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c
index 3bd68a9..3d04ca8 100644
--- a/Modules/pyexpat.c
+++ b/Modules/pyexpat.c
@@ -1792,26 +1792,6 @@
PyDoc_STRVAR(pyexpat_module_documentation,
"Python wrapper for Expat parser.");
-/* Return a Python string that represents the version number without the
- * extra cruft added by revision control, even if the right options were
- * given to the "cvs export" command to make it not include the extra
- * cruft.
- */
-static PyObject *
-get_version_string(void)
-{
- static char *rcsid = "$Revision$";
- char *rev = rcsid;
- int i = 0;
-
- while (!isdigit(Py_CHARMASK(*rev)))
- ++rev;
- while (rev[i] != ' ' && rev[i] != '\0')
- ++i;
-
- return PyString_FromStringAndSize(rev, i);
-}
-
/* Initialization function for the module */
#ifndef MODULE_NAME
@@ -1841,6 +1821,7 @@
PyObject *modelmod_name;
PyObject *model_module;
PyObject *sys_modules;
+ PyObject *version;
static struct PyExpat_CAPI capi;
PyObject* capi_object;
@@ -1872,7 +1853,10 @@
Py_INCREF(&Xmlparsetype);
PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype);
- PyModule_AddObject(m, "__version__", get_version_string());
+ version = PyString_FromString(PY_VERSION);
+ if (!version)
+ return;
+ PyModule_AddObject(m, "__version__", version);
PyModule_AddStringConstant(m, "EXPAT_VERSION",
(char *) XML_ExpatVersion());
{
diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c
index 5192ce7..5a8580c 100644
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -114,7 +114,7 @@
#if defined(_MSC_VER)
max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
- if (v < 0 || v >= FD_SETSIZE) {
+ if (!_PyIsSelectable_fd(v)) {
PyErr_SetString(PyExc_ValueError,
"filedescriptor out of range in select()");
goto finally;
@@ -164,13 +164,6 @@
for (j = 0; fd2obj[j].sentinel >= 0; j++) {
fd = fd2obj[j].fd;
if (FD_ISSET(fd, set)) {
-#ifndef _MSC_VER
- if (fd > FD_SETSIZE) {
- PyErr_SetString(PyExc_SystemError,
- "filedescriptor out of range returned in select()");
- goto finally;
- }
-#endif
o = fd2obj[j].obj;
fd2obj[j].obj = NULL;
/* transfer ownership */
@@ -912,7 +905,7 @@
PyDoc_STRVAR(pyepoll_register_doc,
"register(fd[, eventmask]) -> None\n\
\n\
-Registers a new fd or modifies an already registered fd.\n\
+Registers a new fd or raises an IOError if the fd is already registered.\n\
fd is the target file descriptor of the operation.\n\
events is a bit set composed of the various EPOLL constants; the default\n\
is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c
index d14910a..279a090 100644
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -456,18 +456,14 @@
#include <sys/poll.h>
#endif
-#ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
-/* Platform can select file descriptors beyond FD_SETSIZE */
-#define IS_SELECTABLE(s) 1
-#elif defined(HAVE_POLL)
+#ifdef HAVE_POLL
/* Instead of select(), we'll use poll() since poll() works on any fd. */
#define IS_SELECTABLE(s) 1
/* Can we call select() with this socket without a buffer overrun? */
#else
-/* POSIX says selecting file descriptors beyond FD_SETSIZE
- has undefined behaviour. If there's no timeout left, we don't have to
- call select, so it's a safe, little white lie. */
-#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
+/* If there's no timeout left, we don't have to call select, so it's a safe,
+ * little white lie. */
+#define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
#endif
static PyObject*
@@ -1784,7 +1780,7 @@
PyDoc_STRVAR(gettimeout_doc,
"gettimeout() -> timeout\n\
\n\
-Returns the timeout in floating seconds associated with socket \n\
+Returns the timeout in seconds (float) associated with socket \n\
operations. A timeout of None indicates that timeouts on socket \n\
operations are disabled.");
@@ -2244,8 +2240,10 @@
if (backlog == -1 && PyErr_Occurred())
return NULL;
Py_BEGIN_ALLOW_THREADS
- if (backlog < 1)
- backlog = 1;
+ /* To avoid problems on systems that don't allow a negative backlog
+ * (which doesn't make sense anyway) we force a minimum value of 0. */
+ if (backlog < 0)
+ backlog = 0;
res = listen(s->sock_fd, backlog);
Py_END_ALLOW_THREADS
if (res < 0)
@@ -2258,8 +2256,9 @@
"listen(backlog)\n\
\n\
Enable a server to accept connections. The backlog argument must be at\n\
-least 1; it specifies the number of unaccepted connection that the system\n\
-will allow before refusing new connections.");
+least 0 (if it is lower, it is set to 0); it specifies the number of\n\
+unaccepted connections that the system will allow before refusing new\n\
+connections.");
#ifndef NO_DUP
@@ -2826,14 +2825,24 @@
Py_ssize_t len;
sock_addr_t addrbuf;
int addrlen, n = -1, flags, timeout;
+ int arglen;
flags = 0;
- if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s*iO:sendto",
- &pbuf, &flags, &addro))
- return NULL;
+ arglen = PyTuple_Size(args);
+ switch(arglen) {
+ case 2:
+ PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro);
+ break;
+ case 3:
+ PyArg_ParseTuple(args, "s*iO:sendto", &pbuf, &flags, &addro);
+ break;
+ default:
+ PyErr_Format(PyExc_TypeError, "sendto() takes 2 or 3"
+ " arguments (%d given)", arglen);
}
+ if (PyErr_Occurred())
+ return NULL;
+
buf = pbuf.buf;
len = pbuf.len;
@@ -4239,7 +4248,7 @@
PyDoc_STRVAR(getdefaulttimeout_doc,
"getdefaulttimeout() -> timeout\n\
\n\
-Returns the default timeout in floating seconds for new socket objects.\n\
+Returns the default timeout in seconds (float) for new socket objects.\n\
A value of None indicates that new socket objects have no timeout.\n\
When the socket module is first imported, the default is None.");
@@ -4269,7 +4278,7 @@
PyDoc_STRVAR(setdefaulttimeout_doc,
"setdefaulttimeout(timeout)\n\
\n\
-Set the default timeout in floating seconds for new socket objects.\n\
+Set the default timeout in seconds (float) for new socket objects.\n\
A value of None indicates that new socket objects have no timeout.\n\
When the socket module is first imported, the default is None.");
diff --git a/Modules/threadmodule.c b/Modules/threadmodule.c
index 79e6bab..4e41085 100644
--- a/Modules/threadmodule.c
+++ b/Modules/threadmodule.c
@@ -715,7 +715,7 @@
PyDoc_STRVAR(exit_doc,
"exit()\n\
-(PyThread_exit_thread() is an obsolete synonym)\n\
+(exit_thread() is an obsolete synonym)\n\
\n\
This is synonymous to ``raise SystemExit''. It will cause the current\n\
thread to exit silently unless the exception is caught.");
diff --git a/Modules/unicodedata.c b/Modules/unicodedata.c
index e39a4d6..1445a95 100644
--- a/Modules/unicodedata.c
+++ b/Modules/unicodedata.c
@@ -830,7 +830,7 @@
unsigned long h = 0;
unsigned long ix;
for (i = 0; i < len; i++) {
- h = (h * scale) + (unsigned char) toupper(Py_CHARMASK(s[i]));
+ h = (h * scale) + (unsigned char) Py_TOUPPER(Py_CHARMASK(s[i]));
ix = h & 0xff000000;
if (ix)
h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
@@ -978,7 +978,7 @@
if (!_getucname(self, code, buffer, sizeof(buffer)))
return 0;
for (i = 0; i < namelen; i++) {
- if (toupper(Py_CHARMASK(name[i])) != buffer[i])
+ if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i])
return 0;
}
return buffer[namelen] == '\0';
diff --git a/Modules/zipimport.c b/Modules/zipimport.c
index 9224a68..b7a1b8d 100644
--- a/Modules/zipimport.c
+++ b/Modules/zipimport.c
@@ -798,35 +798,33 @@
/* Return the zlib.decompress function object, or NULL if zlib couldn't
be imported. The function is cached when found, so subsequent calls
- don't import zlib again. Returns a *borrowed* reference.
- XXX This makes zlib.decompress immortal. */
+ don't import zlib again. */
static PyObject *
get_decompress_func(void)
{
- static PyObject *decompress = NULL;
+ static int importing_zlib = 0;
+ PyObject *zlib;
+ PyObject *decompress;
- if (decompress == NULL) {
- PyObject *zlib;
- static int importing_zlib = 0;
-
- if (importing_zlib != 0)
- /* Someone has a zlib.py[co] in their Zip file;
- let's avoid a stack overflow. */
- return NULL;
- importing_zlib = 1;
- zlib = PyImport_ImportModuleNoBlock("zlib");
- importing_zlib = 0;
- if (zlib != NULL) {
- decompress = PyObject_GetAttrString(zlib,
- "decompress");
- Py_DECREF(zlib);
- }
- else
- PyErr_Clear();
- if (Py_VerboseFlag)
- PySys_WriteStderr("# zipimport: zlib %s\n",
- zlib != NULL ? "available": "UNAVAILABLE");
+ if (importing_zlib != 0)
+ /* Someone has a zlib.py[co] in their Zip file;
+ let's avoid a stack overflow. */
+ return NULL;
+ importing_zlib = 1;
+ zlib = PyImport_ImportModuleNoBlock("zlib");
+ importing_zlib = 0;
+ if (zlib != NULL) {
+ decompress = PyObject_GetAttrString(zlib,
+ "decompress");
+ Py_DECREF(zlib);
}
+ else {
+ PyErr_Clear();
+ decompress = NULL;
+ }
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# zipimport: zlib %s\n",
+ zlib != NULL ? "available": "UNAVAILABLE");
return decompress;
}
@@ -911,6 +909,7 @@
goto error;
}
data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
+ Py_DECREF(decompress);
error:
Py_DECREF(raw_data);
return data;
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
index 183f01e..035aa8e 100644
--- a/Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -72,7 +72,13 @@
static void
zlib_error(z_stream zst, int err, char *msg)
{
- const char *zmsg = zst.msg;
+ const char *zmsg = Z_NULL;
+ /* In case of a version mismatch, zst.msg won't be initialized.
+ Check for this case first, before looking at zst.msg. */
+ if (err == Z_VERSION_ERROR)
+ zmsg = "library version mismatch";
+ if (zmsg == Z_NULL)
+ zmsg = zst.msg;
if (zmsg == Z_NULL) {
switch (err) {
case Z_BUF_ERROR:
@@ -535,17 +541,22 @@
Py_END_ALLOW_THREADS
}
- /* Not all of the compressed data could be accommodated in the output buffer
- of specified size. Return the unconsumed tail in an attribute.*/
if(max_length) {
+ /* Not all of the compressed data could be accommodated in a buffer of
+ the specified size. Return the unconsumed tail in an attribute. */
Py_DECREF(self->unconsumed_tail);
self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
self->zst.avail_in);
- if(!self->unconsumed_tail) {
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
- }
+ }
+ else if (PyString_GET_SIZE(self->unconsumed_tail) > 0) {
+ /* All of the compressed data was consumed. Clear unconsumed_tail. */
+ Py_DECREF(self->unconsumed_tail);
+ self->unconsumed_tail = PyString_FromStringAndSize("", 0);
+ }
+ if(!self->unconsumed_tail) {
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
/* The end of the compressed data has been reached, so set the
diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c
index 57471c3..a40c0ab 100644
--- a/Objects/bytearrayobject.c
+++ b/Objects/bytearrayobject.c
@@ -1170,7 +1170,7 @@
"B.find(sub [,start [,end]]) -> int\n\
\n\
Return the lowest index in B where subsection sub is found,\n\
-such that sub is contained within s[start,end]. Optional\n\
+such that sub is contained within B[start,end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
@@ -1240,7 +1240,7 @@
"B.rfind(sub [,start [,end]]) -> int\n\
\n\
Return the highest index in B where subsection sub is found,\n\
-such that sub is contained within s[start,end]. Optional\n\
+such that sub is contained within B[start,end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
diff --git a/Objects/descrobject.c b/Objects/descrobject.c
index 9d735a2..8e7ea7d 100644
--- a/Objects/descrobject.c
+++ b/Objects/descrobject.c
@@ -224,7 +224,8 @@
return NULL;
}
self = PyTuple_GET_ITEM(args, 0);
- if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
+ if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
+ (PyObject *)(descr->d_type))) {
PyErr_Format(PyExc_TypeError,
"descriptor '%.200s' "
"requires a '%.100s' object "
@@ -282,7 +283,8 @@
return NULL;
}
self = PyTuple_GET_ITEM(args, 0);
- if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
+ if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
+ (PyObject *)(descr->d_type))) {
PyErr_Format(PyExc_TypeError,
"descriptor '%.200s' "
"requires a '%.100s' object "
@@ -799,6 +801,20 @@
return PyObject_Str(pp->dict);
}
+static PyObject *
+proxy_repr(proxyobject *pp)
+{
+ PyObject *dictrepr;
+ PyObject *result;
+
+ dictrepr = PyObject_Repr(pp->dict);
+ if (dictrepr == NULL)
+ return NULL;
+ result = PyString_FromFormat("dict_proxy(%s)", PyString_AS_STRING(dictrepr));
+ Py_DECREF(dictrepr);
+ return result;
+}
+
static int
proxy_traverse(PyObject *self, visitproc visit, void *arg)
{
@@ -830,7 +846,7 @@
0, /* tp_getattr */
0, /* tp_setattr */
(cmpfunc)proxy_compare, /* tp_compare */
- 0, /* tp_repr */
+ (reprfunc)proxy_repr, /* tp_repr */
0, /* tp_as_number */
&proxy_as_sequence, /* tp_as_sequence */
&proxy_as_mapping, /* tp_as_mapping */
@@ -1046,7 +1062,8 @@
assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type));
descr = (PyWrapperDescrObject *)d;
- assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type)));
+ assert(_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
+ (PyObject *)(descr->d_type)));
wp = PyObject_GC_New(wrapperobject, &wrappertype);
if (wp != NULL) {
diff --git a/Objects/fileobject.c b/Objects/fileobject.c
index 974d642..edd839e 100644
--- a/Objects/fileobject.c
+++ b/Objects/fileobject.c
@@ -468,28 +468,34 @@
PyObject *
PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
{
- PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
- NULL, NULL);
- if (f != NULL) {
- PyObject *o_name = PyString_FromString(name);
- if (o_name == NULL)
- return NULL;
- if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
- Py_DECREF(f);
- f = NULL;
- }
- Py_DECREF(o_name);
+ PyFileObject *f;
+ PyObject *o_name;
+
+ f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
+ if (f == NULL)
+ return NULL;
+ o_name = PyString_FromString(name);
+ if (o_name == NULL) {
+ if (close != NULL && fp != NULL)
+ close(fp);
+ Py_DECREF(f);
+ return NULL;
}
- return (PyObject *) f;
+ if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
+ Py_DECREF(f);
+ Py_DECREF(o_name);
+ return NULL;
+ }
+ Py_DECREF(o_name);
+ return (PyObject *)f;
}
PyObject *
PyFile_FromString(char *name, char *mode)
{
- extern int fclose(FILE *);
PyFileObject *f;
- f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
+ f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, NULL);
if (f != NULL) {
if (open_the_file(f, name, mode) == NULL) {
Py_DECREF(f);
diff --git a/Objects/intobject.c b/Objects/intobject.c
index 7d70bfb..e518e74 100644
--- a/Objects/intobject.c
+++ b/Objects/intobject.c
@@ -751,7 +751,13 @@
while (iw > 0) {
prev = ix; /* Save value for overflow check */
if (iw & 1) {
- ix = ix*temp;
+ /*
+ * The (unsigned long) cast below ensures that the multiplication
+ * is interpreted as an unsigned operation rather than a signed one
+ * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour
+ * from signed arithmetic overflow (C99 6.5p5). See issue #12973.
+ */
+ ix = (unsigned long)ix * temp;
if (temp == 0)
break; /* Avoid ix / 0 */
if (ix / temp != prev) {
@@ -764,7 +770,7 @@
iw >>= 1; /* Shift exponent down by 1 bit */
if (iw==0) break;
prev = temp;
- temp *= temp; /* Square the value of temp */
+ temp = (unsigned long)temp * temp; /* Square the value of temp */
if (prev != 0 && temp / prev != prev) {
return PyLong_Type.tp_as_number->nb_power(
(PyObject *)v, (PyObject *)w, (PyObject *)z);
diff --git a/Objects/listobject.c b/Objects/listobject.c
index 08f7880..f753643 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -58,7 +58,7 @@
if (newsize == 0)
new_allocated = 0;
items = self->ob_item;
- if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
+ if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
PyMem_RESIZE(items, PyObject *, new_allocated);
else
items = NULL;
@@ -551,9 +551,9 @@
PyObject *elem;
if (n < 0)
n = 0;
- size = Py_SIZE(a) * n;
- if (n && size/n != Py_SIZE(a))
+ if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
return PyErr_NoMemory();
+ size = Py_SIZE(a) * n;
if (size == 0)
return PyList_New(0);
np = (PyListObject *) PyList_New(size);
diff --git a/Objects/object.c b/Objects/object.c
index b6ad5de..94a18d3 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -1905,13 +1905,26 @@
_dir_object(PyObject *obj)
{
PyObject *result = NULL;
- PyObject *dirfunc = PyObject_GetAttrString((PyObject *)obj->ob_type,
- "__dir__");
+ static PyObject *dir_str = NULL;
+ PyObject *dirfunc;
assert(obj);
+ if (PyInstance_Check(obj)) {
+ dirfunc = PyObject_GetAttrString(obj, "__dir__");
+ if (dirfunc == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ }
+ else {
+ dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
+ if (PyErr_Occurred())
+ return NULL;
+ }
if (dirfunc == NULL) {
/* use default implementation */
- PyErr_Clear();
if (PyModule_Check(obj))
result = _specialized_dir_module(obj);
else if (PyType_Check(obj) || PyClass_Check(obj))
@@ -1921,7 +1934,7 @@
}
else {
/* use __dir__ */
- result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
+ result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
Py_DECREF(dirfunc);
if (result == NULL)
return NULL;
diff --git a/Objects/stringobject.c b/Objects/stringobject.c
index 693f773..d6c4f77 100644
--- a/Objects/stringobject.c
+++ b/Objects/stringobject.c
@@ -1727,7 +1727,7 @@
"S.find(sub [,start [,end]]) -> int\n\
\n\
Return the lowest index in S where substring sub is found,\n\
-such that sub is contained within s[start:end]. Optional\n\
+such that sub is contained within S[start:end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
@@ -1766,7 +1766,7 @@
"S.rfind(sub [,start [,end]]) -> int\n\
\n\
Return the highest index in S where substring sub is found,\n\
-such that sub is contained within s[start:end]. Optional\n\
+such that sub is contained within S[start:end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
@@ -2173,7 +2173,9 @@
Return a copy of the string S, where all characters occurring\n\
in the optional argument deletechars are removed, and the\n\
remaining characters have been mapped through the given\n\
-translation table, which must be a string of length 256.");
+translation table, which must be a string of length 256 or None.\n\
+If the table argument is None, no translation is applied and\n\
+the operation simply removes the characters in deletechars.");
static PyObject *
string_translate(PyStringObject *self, PyObject *args)
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 30afc24..7c98cfd 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -1013,6 +1013,8 @@
assert(basedealloc);
basedealloc(self);
+ PyType_Modified(type);
+
/* Can't reference self beyond this point */
Py_DECREF(type);
@@ -2233,8 +2235,10 @@
(add_weak && strcmp(s, "__weakref__") == 0))
continue;
tmp =_Py_Mangle(name, tmp);
- if (!tmp)
+ if (!tmp) {
+ Py_DECREF(newslots);
goto bad_slots;
+ }
PyList_SET_ITEM(newslots, j, tmp);
j++;
}
@@ -2665,9 +2669,9 @@
{"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
{"__instancecheck__", type___instancecheck__, METH_O,
- PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
+ PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")},
{"__subclasscheck__", type___subclasscheck__, METH_O,
- PyDoc_STR("__subclasscheck__() -> check if a class is a subclass")},
+ PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")},
{0}
};
@@ -2978,7 +2982,7 @@
unaryfunc f;
f = Py_TYPE(self)->tp_repr;
- if (f == NULL)
+ if (f == NULL || f == object_str)
f = object_repr;
return f(self);
}
@@ -3490,7 +3494,7 @@
{"__format__", object_format, METH_VARARGS,
PyDoc_STR("default object formatter")},
{"__sizeof__", object_sizeof, METH_NOARGS,
- PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
+ PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")},
{0}
};
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index b2332a5..4d6864d 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -5485,13 +5485,13 @@
if (len == 0)
return 0;
- if (Py_UNICODE_ISLOWER(*s)) {
+ if (!Py_UNICODE_ISUPPER(*s)) {
*s = Py_UNICODE_TOUPPER(*s);
status = 1;
}
s++;
while (--len > 0) {
- if (Py_UNICODE_ISUPPER(*s)) {
+ if (!Py_UNICODE_ISLOWER(*s)) {
*s = Py_UNICODE_TOLOWER(*s);
status = 1;
}
@@ -6491,7 +6491,7 @@
"S.find(sub [,start [,end]]) -> int\n\
\n\
Return the lowest index in S where substring sub is found,\n\
-such that sub is contained within s[start:end]. Optional\n\
+such that sub is contained within S[start:end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
@@ -7226,7 +7226,7 @@
"S.rfind(sub [,start [,end]]) -> int\n\
\n\
Return the highest index in S where substring sub is found,\n\
-such that sub is contained within s[start:end]. Optional\n\
+such that sub is contained within S[start:end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
\n\
Return -1 on failure.");
diff --git a/Parser/asdl_c.py b/Parser/asdl_c.py
index 634ad29..6a46549 100755
--- a/Parser/asdl_c.py
+++ b/Parser/asdl_c.py
@@ -800,8 +800,25 @@
return 0;
}
-#define obj2ast_identifier obj2ast_object
-#define obj2ast_string obj2ast_object
+static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena)
+{
+ if (!PyString_CheckExact(obj) && obj != Py_None) {
+ PyErr_Format(PyExc_TypeError,
+ "AST identifier must be of type str");
+ return 1;
+ }
+ return obj2ast_object(obj, out, arena);
+}
+
+static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena)
+{
+ if (!PyString_CheckExact(obj) && !PyUnicode_CheckExact(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "AST string must be of type str or unicode");
+ return 1;
+ }
+ return obj2ast_object(obj, out, arena);
+}
static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
{
@@ -903,9 +920,6 @@
self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
-def parse_version(mod):
- return mod.version.value[12:-3]
-
class ASTModuleVisitor(PickleVisitor):
def visitModule(self, mod):
@@ -922,7 +936,7 @@
self.emit("return;", 2)
# Value of version: "$Revision$"
self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
- % parse_version(mod), 1)
+ % mod.version, 1)
self.emit("return;", 2)
for dfn in mod.dfns:
self.visit(dfn)
@@ -1160,6 +1174,7 @@
argv0 = os.sep.join(components[-2:])
auto_gen_msg = common_msg % argv0
mod = asdl.parse(srcfile)
+ mod.version = "82160"
if not asdl.check(mod):
sys.exit(1)
if INC_DIR:
@@ -1181,7 +1196,7 @@
p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
f = open(p, "wb")
f.write(auto_gen_msg)
- f.write(c_file_msg % parse_version(mod))
+ f.write(c_file_msg % mod.version)
f.write('#include "Python.h"\n')
f.write('#include "%s-ast.h"\n' % mod.name)
f.write('\n')
diff --git a/Parser/myreadline.c b/Parser/myreadline.c
index 8a76e0c..07c1d44 100644
--- a/Parser/myreadline.c
+++ b/Parser/myreadline.c
@@ -44,6 +44,7 @@
if (PyOS_InputHook != NULL)
(void)(PyOS_InputHook)();
errno = 0;
+ clearerr(fp);
p = fgets(buf, len, fp);
if (p != NULL)
return 0; /* No error */
@@ -77,6 +78,7 @@
}
#endif /* MS_WINDOWS */
if (feof(fp)) {
+ clearerr(fp);
return -1; /* EOF */
}
#ifdef EINTR
diff --git a/Python/Python-ast.c b/Python/Python-ast.c
index 701ac48..dcfde3c 100644
--- a/Python/Python-ast.c
+++ b/Python/Python-ast.c
@@ -594,8 +594,25 @@
return 0;
}
-#define obj2ast_identifier obj2ast_object
-#define obj2ast_string obj2ast_object
+static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena)
+{
+ if (!PyString_CheckExact(obj) && obj != Py_None) {
+ PyErr_Format(PyExc_TypeError,
+ "AST identifier must be of type str");
+ return 1;
+ }
+ return obj2ast_object(obj, out, arena);
+}
+
+static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena)
+{
+ if (!PyString_CheckExact(obj) && !PyUnicode_CheckExact(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "AST string must be of type str or unicode");
+ return 1;
+ }
+ return obj2ast_object(obj, out, arena);
+}
static int obj2ast_int(PyObject* obj, int* out, PyArena* arena)
{
diff --git a/Python/_warnings.c b/Python/_warnings.c
index 88be7db..445ff6b 100644
--- a/Python/_warnings.c
+++ b/Python/_warnings.c
@@ -491,7 +491,7 @@
/* Setup filename. */
*filename = PyDict_GetItemString(globals, "__file__");
- if (*filename != NULL) {
+ if (*filename != NULL && PyString_Check(*filename)) {
Py_ssize_t len = PyString_Size(*filename);
const char *file_str = PyString_AsString(*filename);
if (file_str == NULL || (len < 0 && PyErr_Occurred()))
@@ -514,6 +514,7 @@
}
else {
const char *module_str = PyString_AsString(*module);
+ *filename = NULL;
if (module_str && strcmp(module_str, "__main__") == 0) {
PyObject *argv = PySys_GetObject("argv");
if (argv != NULL && PyList_Size(argv) > 0) {
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
index 764ae87..a9a7ad1 100644
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -224,7 +224,7 @@
static PyObject *
builtin_callable(PyObject *self, PyObject *v)
{
- if (PyErr_WarnPy3k("callable() not supported in 3.x; "
+ if (PyErr_WarnPy3k("callable() not supported in 3.1; "
"use isinstance(x, collections.Callable)", 1) < 0)
return NULL;
return PyBool_FromLong((long)PyCallable_Check(v));
@@ -604,7 +604,7 @@
}
PyDoc_STRVAR(divmod_doc,
-"divmod(x, y) -> (div, mod)\n\
+"divmod(x, y) -> (quotient, remainder)\n\
\n\
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
diff --git a/Python/ceval.c b/Python/ceval.c
index 10dd3a1..06ada97 100644
--- a/Python/ceval.c
+++ b/Python/ceval.c
@@ -3515,9 +3515,17 @@
Py_DECREF(tmp);
}
- if (PyExceptionClass_Check(type))
+ if (PyExceptionClass_Check(type)) {
PyErr_NormalizeException(&type, &value, &tb);
-
+ if (!PyExceptionInstance_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "calling %s() should have returned an instance of "
+ "BaseException, not '%s'",
+ ((PyTypeObject *)type)->tp_name,
+ Py_TYPE(value)->tp_name);
+ goto raise_error;
+ }
+ }
else if (PyExceptionInstance_Check(type)) {
/* Raising an instance. The value should be a dummy. */
if (value != Py_None) {
diff --git a/Python/codecs.c b/Python/codecs.c
index 57bd0f4..7334eb3 100644
--- a/Python/codecs.c
+++ b/Python/codecs.c
@@ -70,7 +70,7 @@
if (ch == ' ')
ch = '-';
else
- ch = tolower(Py_CHARMASK(ch));
+ ch = Py_TOLOWER(Py_CHARMASK(ch));
p[i] = ch;
}
return v;
diff --git a/Python/getargs.c b/Python/getargs.c
index 7c3e9fa..eccdc9b 100644
--- a/Python/getargs.c
+++ b/Python/getargs.c
@@ -585,7 +585,17 @@
#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\
if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
else q=va_arg(*p_va, int*);
-#define STORE_SIZE(s) if (flags & FLAG_SIZE_T) *q2=s; else *q=s;
+#define STORE_SIZE(s) \
+ if (flags & FLAG_SIZE_T) \
+ *q2=s; \
+ else { \
+ if (INT_MAX < s) { \
+ PyErr_SetString(PyExc_OverflowError, \
+ "size does not fit in an int"); \
+ return converterr("", arg, msgbuf, bufsize); \
+ } \
+ *q=s; \
+ }
#define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q)
const char *format = *p_format;
@@ -984,10 +994,11 @@
if (*format == '#') {
FETCH_SIZE;
assert(0); /* XXX redundant with if-case */
- if (arg == Py_None)
- *q = 0;
- else
- *q = PyString_Size(arg);
+ if (arg == Py_None) {
+ STORE_SIZE(0);
+ } else {
+ STORE_SIZE(PyString_Size(arg));
+ }
format++;
}
else if (*p != NULL &&
diff --git a/Python/import.c b/Python/import.c
index 990ee51..c60ecfe 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -1235,7 +1235,7 @@
meta_path = PySys_GetObject("meta_path");
if (meta_path == NULL || !PyList_Check(meta_path)) {
- PyErr_SetString(PyExc_ImportError,
+ PyErr_SetString(PyExc_RuntimeError,
"sys.meta_path must be a list of "
"import hooks");
return NULL;
@@ -1304,14 +1304,14 @@
path = PySys_GetObject("path");
}
if (path == NULL || !PyList_Check(path)) {
- PyErr_SetString(PyExc_ImportError,
+ PyErr_SetString(PyExc_RuntimeError,
"sys.path must be a list of directory names");
return NULL;
}
path_hooks = PySys_GetObject("path_hooks");
if (path_hooks == NULL || !PyList_Check(path_hooks)) {
- PyErr_SetString(PyExc_ImportError,
+ PyErr_SetString(PyExc_RuntimeError,
"sys.path_hooks must be a list of "
"import hooks");
return NULL;
@@ -1319,7 +1319,7 @@
path_importer_cache = PySys_GetObject("path_importer_cache");
if (path_importer_cache == NULL ||
!PyDict_Check(path_importer_cache)) {
- PyErr_SetString(PyExc_ImportError,
+ PyErr_SetString(PyExc_RuntimeError,
"sys.path_importer_cache must be a dict");
return NULL;
}
@@ -2064,7 +2064,9 @@
{
PyObject *result;
PyObject *modules;
+#ifdef WITH_THREAD
long me;
+#endif
/* Try to get the module from sys.modules[name] */
modules = PyImport_GetModuleDict();
@@ -2843,10 +2845,8 @@
return NULL;
if (fp != NULL) {
fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
- if (fob == NULL) {
- fclose(fp);
+ if (fob == NULL)
return NULL;
- }
}
else {
fob = Py_None;
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
index 87ffb39..bfb7fca 100644
--- a/Python/pythonrun.c
+++ b/Python/pythonrun.c
@@ -76,7 +76,7 @@
int Py_DebugFlag; /* Needed by parser.c */
int Py_VerboseFlag; /* Needed by import.c */
int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
-int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
+int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
int Py_NoSiteFlag; /* Suppress 'import site' */
int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
index 00b3aa4..692805b 100644
--- a/Python/sysmodule.c
+++ b/Python/sysmodule.c
@@ -466,6 +466,7 @@
{
if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
return NULL;
+ _Py_Ticker = _Py_CheckInterval;
Py_INCREF(Py_None);
return Py_None;
}
diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h
index ef49a30..44e2552 100644
--- a/Python/thread_pthread.h
+++ b/Python/thread_pthread.h
@@ -18,6 +18,18 @@
#ifndef THREAD_STACK_SIZE
#define THREAD_STACK_SIZE 0 /* use default stack size */
#endif
+
+#if (defined(__APPLE__) || defined(__FreeBSD__)) && defined(THREAD_STACK_SIZE) && THREAD_STACK_SIZE == 0
+ /* The default stack size for new threads on OSX is small enough that
+ * we'll get hard crashes instead of 'maximum recursion depth exceeded'
+ * exceptions.
+ *
+ * The default stack size below is the minimal stack size where a
+ * simple recursive function doesn't cause a hard crash.
+ */
+#undef THREAD_STACK_SIZE
+#define THREAD_STACK_SIZE 0x400000
+#endif
/* for safety, ensure a viable minimum stacksize */
#define THREAD_STACK_MIN 0x8000 /* 32kB */
#else /* !_POSIX_THREAD_ATTR_STACKSIZE */
diff --git a/README b/README
index da5753c..680e5e3 100644
--- a/README
+++ b/README
@@ -1,4 +1,4 @@
-This is Python version 2.7.1
+This is Python version 2.7.2
============================
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
diff --git a/Tools/iobench/iobench.py b/Tools/iobench/iobench.py
index 92b4ffa..6211e95 100644
--- a/Tools/iobench/iobench.py
+++ b/Tools/iobench/iobench.py
@@ -358,7 +358,7 @@
with text_open(name, "r") as f:
return f.read()
run_test_family(modify_tests, "b", text_files,
- lambda fn: open(fn, "r+"), make_test_source)
+ lambda fn: text_open(fn, "r+"), make_test_source)
def prepare_files():
diff --git a/Tools/msi/msi.py b/Tools/msi/msi.py
index 5679fdb..f01aa7f 100644
--- a/Tools/msi/msi.py
+++ b/Tools/msi/msi.py
@@ -505,7 +505,7 @@
" would still be Python for DOS.")
c = exit_dialog.text("warning", 135, 200, 220, 40, 0x30003,
- "{\\VerdanaRed9}Warning: Python 2.7.x is the last "
+ "{\\VerdanaRed9}Warning: Python 3.3.0 is the last "
"Python release for Windows 2000.")
c.condition("Hide", "VersionNT > 500")
diff --git a/Tools/msi/uuids.py b/Tools/msi/uuids.py
index 1162040..681de12 100644
--- a/Tools/msi/uuids.py
+++ b/Tools/msi/uuids.py
@@ -53,4 +53,6 @@
'2.7.1121':'{60a4036a-374c-4fd2-84b9-bfae7db03931}', # 2.7.1rc1
'2.7.1122':'{5965e7d1-5584-4de9-b13a-694e0b2ee3a6}', # 2.7.1rc2
'2.7.1150':'{32939827-d8e5-470a-b126-870db3c69fdf}', # 2.7.1
+ '2.7.2121':'{B2E1F06E-F719-4786-972A-488A336EB2A0}', # 2.7.2rc1
+ '2.7.2150':'{2E295B5B-1AD4-4d36-97C2-A316084722CF}', # 2.7.2
}
diff --git a/Tools/scripts/analyze_dxp.py b/Tools/scripts/analyze_dxp.py
old mode 100644
new mode 100755
index bde931e..1224383
--- a/Tools/scripts/analyze_dxp.py
+++ b/Tools/scripts/analyze_dxp.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
"""
Some helper functions to analyze the output of sys.getdxp() (which is
only available if Python was built with -DDYNAMIC_EXECUTION_PROFILE).
diff --git a/Tools/scripts/byext.py b/Tools/scripts/byext.py
index 09610b0..138d8dd 100755
--- a/Tools/scripts/byext.py
+++ b/Tools/scripts/byext.py
@@ -23,12 +23,11 @@
def statdir(self, dir):
self.addstats("<dir>", "dirs", 1)
try:
- names = os.listdir(dir)
- except os.error, err:
+ names = sorted(os.listdir(dir))
+ except os.error as err:
sys.stderr.write("Can't list %s: %s\n" % (dir, err))
self.addstats("<dir>", "unlistable", 1)
return
- names.sort()
for name in names:
if name.startswith(".#"):
continue # Skip CVS temp files
@@ -53,14 +52,14 @@
self.addstats(ext, "files", 1)
try:
f = open(filename, "rb")
- except IOError, err:
+ except IOError as err:
sys.stderr.write("Can't open %s: %s\n" % (filename, err))
self.addstats(ext, "unopenable", 1)
return
data = f.read()
f.close()
self.addstats(ext, "bytes", len(data))
- if '\0' in data:
+ if b'\0' in data:
self.addstats(ext, "binary", 1)
return
if not data:
@@ -77,14 +76,12 @@
d[key] = d.get(key, 0) + n
def report(self):
- exts = self.stats.keys()
- exts.sort()
+ exts = sorted(self.stats.keys())
# Get the column keys
columns = {}
for ext in exts:
columns.update(self.stats[ext])
- cols = columns.keys()
- cols.sort()
+ cols = sorted(columns.keys())
colwidth = {}
colwidth["ext"] = max([len(ext) for ext in exts])
minwidth = 6
@@ -109,14 +106,14 @@
cols.insert(0, "ext")
def printheader():
for col in cols:
- print "%*s" % (colwidth[col], col),
- print
+ print("%*s" % (colwidth[col], col), end=" ")
+ print()
printheader()
for ext in exts:
for col in cols:
value = self.stats[ext].get(col, "")
- print "%*s" % (colwidth[col], value),
- print
+ print("%*s" % (colwidth[col], value), end=" ")
+ print()
printheader() # Another header at the bottom
def main():
diff --git a/Tools/scripts/cleanfuture.py b/Tools/scripts/cleanfuture.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/combinerefs.py b/Tools/scripts/combinerefs.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/db2pickle.py b/Tools/scripts/db2pickle.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/diff.py b/Tools/scripts/diff.py
old mode 100644
new mode 100755
index 52dcab1..513e2a7
--- a/Tools/scripts/diff.py
+++ b/Tools/scripts/diff.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
""" Command line interface to difflib.py providing diffs in four formats:
* ndiff: lists every line and highlights interline changes.
diff --git a/Tools/scripts/find_recursionlimit.py b/Tools/scripts/find_recursionlimit.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/hotshotmain.py b/Tools/scripts/hotshotmain.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/mailerdaemon.py b/Tools/scripts/mailerdaemon.py
old mode 100644
new mode 100755
index 85f90aa..a1eeaad
--- a/Tools/scripts/mailerdaemon.py
+++ b/Tools/scripts/mailerdaemon.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
"""mailerdaemon - classes to parse mailer-daemon messages"""
import rfc822
diff --git a/Tools/scripts/md5sum.py b/Tools/scripts/md5sum.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/patchcheck.py b/Tools/scripts/patchcheck.py
old mode 100644
new mode 100755
index bc8bc79..2834fef
--- a/Tools/scripts/patchcheck.py
+++ b/Tools/scripts/patchcheck.py
@@ -1,13 +1,18 @@
+#!/usr/bin/env python
import re
import sys
import shutil
import os.path
import subprocess
+import sysconfig
import reindent
import untabify
+SRCDIR = sysconfig.get_config_var('srcdir')
+
+
def n_files_str(count):
"""Return 'N file(s)' with the proper plurality on 'file'."""
return "{} file{}".format(count, "s" if count != 1 else "")
@@ -35,7 +40,7 @@
info=lambda x: n_files_str(len(x)))
def changed_files():
"""Get the list of changed or added files from the VCS."""
- if os.path.isdir('.hg'):
+ if os.path.isdir(os.path.join(SRCDIR, '.hg')):
vcs = 'hg'
cmd = 'hg status --added --modified --no-status'
elif os.path.isdir('.svn'):
@@ -74,7 +79,7 @@
reindent.makebackup = False # No need to create backups.
fixed = []
for path in (x for x in file_paths if x.endswith('.py')):
- if reindent.check(path):
+ if reindent.check(os.path.join(SRCDIR, path)):
fixed.append(path)
return fixed
@@ -84,10 +89,11 @@
"""Report if any C files """
fixed = []
for path in file_paths:
- with open(path, 'r') as f:
+ abspath = os.path.join(SRCDIR, path)
+ with open(abspath, 'r') as f:
if '\t' not in f.read():
continue
- untabify.process(path, 8, verbose=False)
+ untabify.process(abspath, 8, verbose=False)
fixed.append(path)
return fixed
@@ -98,13 +104,14 @@
def normalize_docs_whitespace(file_paths):
fixed = []
for path in file_paths:
+ abspath = os.path.join(SRCDIR, path)
try:
- with open(path, 'rb') as f:
+ with open(abspath, 'rb') as f:
lines = f.readlines()
new_lines = [ws_re.sub(br'\1', line) for line in lines]
if new_lines != lines:
- shutil.copyfile(path, path + '.bak')
- with open(path, 'wb') as f:
+ shutil.copyfile(abspath, abspath + '.bak')
+ with open(abspath, 'wb') as f:
f.writelines(new_lines)
fixed.append(path)
except Exception as err:
@@ -150,8 +157,9 @@
reported_news(special_files)
# Test suite run and passed.
- print
- print "Did you run the test suite?"
+ if python_files or c_files:
+ print
+ print "Did you run the test suite?"
if __name__ == '__main__':
diff --git a/Tools/scripts/pickle2db.py b/Tools/scripts/pickle2db.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/pysource.py b/Tools/scripts/pysource.py
old mode 100644
new mode 100755
diff --git a/Tools/scripts/redemo.py b/Tools/scripts/redemo.py
old mode 100644
new mode 100755
index de7f3c4..2b5ade4
--- a/Tools/scripts/redemo.py
+++ b/Tools/scripts/redemo.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
"""Basic regular expression demostration facility (Perl style syntax)."""
from Tkinter import *
diff --git a/Tools/scripts/reindent.py b/Tools/scripts/reindent.py
index 3e9affb..df15edb 100755
--- a/Tools/scripts/reindent.py
+++ b/Tools/scripts/reindent.py
@@ -35,7 +35,7 @@
The backup file is a copy of the one that is being reindented. The ".bak"
file is generated with shutil.copy(), but some corner cases regarding
-user/group and permissions could leave the backup file more readable that
+user/group and permissions could leave the backup file more readable than
you'd prefer. You can always use the --nobackup option to prevent this.
"""
@@ -44,6 +44,7 @@
import tokenize
import os, shutil
import sys
+import io
verbose = 0
recurse = 0
@@ -108,13 +109,19 @@
if verbose:
print "checking", file, "...",
try:
- f = open(file)
+ f = io.open(file)
except IOError, msg:
errprint("%s: I/O Error: %s" % (file, str(msg)))
return
r = Reindenter(f)
f.close()
+
+ newline = r.newlines
+ if isinstance(newline, tuple):
+ errprint("%s: mixed newlines detected; cannot process file" % file)
+ return
+
if r.run():
if verbose:
print "changed."
@@ -126,7 +133,7 @@
shutil.copyfile(file, bak)
if verbose:
print "backed up", file, "to", bak
- f = open(file, "w")
+ f = io.open(file, "w", newline=newline)
r.write(f)
f.close()
if verbose:
@@ -173,6 +180,10 @@
# indeed, they're our headache!
self.stats = []
+ # Save the newlines found in the file so they can be used to
+ # create output without mutating the newlines.
+ self.newlines = f.newlines
+
def run(self):
tokenize.tokenize(self.getline, self.tokeneater)
# Remove trailing empty lines.
diff --git a/configure b/configure
index 29ce00c..7d6423a 100755
--- a/configure
+++ b/configure
@@ -1,7 +1,7 @@
#! /bin/sh
# From configure.in Revision.
# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.68 for python 2.7.
+# Generated by GNU Autoconf 2.67 for python 2.7.
#
# Report bugs to <http://bugs.python.org/>.
#
@@ -92,7 +92,6 @@
IFS=" "" $as_nl"
# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
case $0 in #((
*[\\/]* ) as_myself=$0 ;;
*) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -218,18 +217,11 @@
# We cannot yet assume a decent shell, so we have to provide a
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
- # Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
export CONFIG_SHELL
- case $- in # ((((
- *v*x* | *x*v* ) as_opts=-vx ;;
- *v* ) as_opts=-v ;;
- *x* ) as_opts=-x ;;
- * ) as_opts= ;;
- esac
- exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
+ exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
fi
if test x$as_have_required = xno; then :
@@ -1182,7 +1174,7 @@
$as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
$as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
- : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
+ : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
;;
esac
@@ -1519,7 +1511,7 @@
if $ac_init_version; then
cat <<\_ACEOF
python configure 2.7
-generated by GNU Autoconf 2.68
+generated by GNU Autoconf 2.67
Copyright (C) 2010 Free Software Foundation, Inc.
This configure script is free software; the Free Software Foundation
@@ -1565,7 +1557,7 @@
ac_retval=1
fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
as_fn_set_status $ac_retval
} # ac_fn_c_try_compile
@@ -1602,7 +1594,7 @@
ac_retval=1
fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
as_fn_set_status $ac_retval
} # ac_fn_c_try_cpp
@@ -1615,10 +1607,10 @@
ac_fn_c_check_header_mongrel ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if eval \${$3+:} false; then :
+ if eval "test \"\${$3+set}\"" = set; then :
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
fi
eval ac_res=\$$3
@@ -1685,7 +1677,7 @@
esac
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
eval "$3=\$ac_header_compiler"
@@ -1694,7 +1686,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_header_mongrel
@@ -1735,7 +1727,7 @@
ac_retval=$ac_status
fi
rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
as_fn_set_status $ac_retval
} # ac_fn_c_try_run
@@ -1749,7 +1741,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -1767,7 +1759,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_header_compile
@@ -1812,7 +1804,7 @@
# interfere with the next link command; also delete a directory that is
# left behind by Apple's compiler. We do this before executing the actions.
rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
as_fn_set_status $ac_retval
} # ac_fn_c_try_link
@@ -1826,7 +1818,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
eval "$3=no"
@@ -1867,7 +1859,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_type
@@ -1880,7 +1872,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5
$as_echo_n "checking for uint$2_t... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
eval "$3=no"
@@ -1920,7 +1912,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_find_uintX_t
@@ -1933,7 +1925,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for int$2_t" >&5
$as_echo_n "checking for int$2_t... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
eval "$3=no"
@@ -1994,7 +1986,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_find_intX_t
@@ -2171,7 +2163,7 @@
rm -f conftest.val
fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
as_fn_set_status $ac_retval
} # ac_fn_c_compute_int
@@ -2184,7 +2176,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2239,7 +2231,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_func
@@ -2252,7 +2244,7 @@
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5
$as_echo_n "checking for $2.$3... " >&6; }
-if eval \${$4+:} false; then :
+if eval "test \"\${$4+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2296,7 +2288,7 @@
eval ac_res=\$$4
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_member
@@ -2311,7 +2303,7 @@
as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'`
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5
$as_echo_n "checking whether $as_decl_name is declared... " >&6; }
-if eval \${$3+:} false; then :
+if eval "test \"\${$3+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2342,7 +2334,7 @@
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+ eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
} # ac_fn_c_check_decl
cat >config.log <<_ACEOF
@@ -2350,7 +2342,7 @@
running configure, to aid debugging if configure makes a mistake.
It was created by python $as_me 2.7, which was
-generated by GNU Autoconf 2.68. Invocation command line was
+generated by GNU Autoconf 2.67. Invocation command line was
$ $0 $@
@@ -2608,7 +2600,7 @@
|| { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
fi
done
@@ -3003,6 +2995,7 @@
MACHDEP="$ac_md_system$ac_md_release"
case $MACHDEP in
+ linux*) MACHDEP="linux2";;
cygwin*) MACHDEP="cygwin";;
darwin*) MACHDEP="darwin";;
atheos*) MACHDEP="atheos";;
@@ -3026,7 +3019,7 @@
# Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish.
# In addition, Stefan Krah confirms that issue #1244610 exists through
# OpenBSD 4.6, but is fixed in 4.7.
- OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0123456])
+ OpenBSD/2.* | OpenBSD/3.* | OpenBSD/4.[0123456])
define_xopen_source=no
# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
# also defined. This can be overridden by defining _BSD_SOURCE
@@ -3035,7 +3028,7 @@
$as_echo "#define _BSD_SOURCE 1" >>confdefs.h
;;
- OpenBSD/4.[789])
+ OpenBSD/*)
# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
# also defined. This can be overridden by defining _BSD_SOURCE
# As this has a different meaning on Linux, only define it on OpenBSD
@@ -3248,7 +3241,7 @@
set dummy ${ac_tool_prefix}gcc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
+if test "${ac_cv_prog_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
@@ -3288,7 +3281,7 @@
set dummy gcc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$ac_ct_CC"; then
@@ -3341,7 +3334,7 @@
set dummy ${ac_tool_prefix}cc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
+if test "${ac_cv_prog_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
@@ -3381,7 +3374,7 @@
set dummy cc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
+if test "${ac_cv_prog_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
@@ -3440,7 +3433,7 @@
set dummy $ac_tool_prefix$ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
+if test "${ac_cv_prog_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
@@ -3484,7 +3477,7 @@
set dummy $ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$ac_ct_CC"; then
@@ -3539,7 +3532,7 @@
test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
# Provide some information about the compiler.
$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
@@ -3654,7 +3647,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
$as_echo "yes" >&6; }
@@ -3697,7 +3690,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
fi
rm -f conftest conftest$ac_cv_exeext
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
@@ -3756,7 +3749,7 @@
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot run C compiled programs.
If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
fi
fi
fi
@@ -3767,7 +3760,7 @@
ac_clean_files=$ac_clean_files_save
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
+if test "${ac_cv_objext+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -3808,7 +3801,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
fi
rm -f conftest.$ac_cv_objext conftest.$ac_ext
fi
@@ -3818,7 +3811,7 @@
ac_objext=$OBJEXT
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
+if test "${ac_cv_c_compiler_gnu+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -3855,7 +3848,7 @@
ac_save_CFLAGS=$CFLAGS
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
+if test "${ac_cv_prog_cc_g+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_c_werror_flag=$ac_c_werror_flag
@@ -3933,7 +3926,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
+if test "${ac_cv_prog_cc_c89+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_cv_prog_cc_c89=no
@@ -4072,7 +4065,7 @@
set dummy g++; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_CXX+:} false; then :
+if test "${ac_cv_path_CXX+set}" = set; then :
$as_echo_n "(cached) " >&6
else
case $CXX in
@@ -4113,7 +4106,7 @@
set dummy c++; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_CXX+:} false; then :
+if test "${ac_cv_path_CXX+set}" = set; then :
$as_echo_n "(cached) " >&6
else
case $CXX in
@@ -4164,7 +4157,7 @@
set dummy $ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CXX+:} false; then :
+if test "${ac_cv_prog_CXX+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CXX"; then
@@ -4235,7 +4228,7 @@
CPP=
fi
if test -z "$CPP"; then
- if ${ac_cv_prog_CPP+:} false; then :
+ if test "${ac_cv_prog_CPP+set}" = set; then :
$as_echo_n "(cached) " >&6
else
# Double quotes because CPP needs to be expanded
@@ -4351,7 +4344,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
fi
ac_ext=c
@@ -4363,7 +4356,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
+if test "${ac_cv_path_GREP+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -z "$GREP"; then
@@ -4426,7 +4419,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
+if test "${ac_cv_path_EGREP+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
@@ -4493,7 +4486,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
+if test "${ac_cv_header_stdc+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -4622,7 +4615,7 @@
ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default"
-if test "x$ac_cv_header_minix_config_h" = xyes; then :
+if test "x$ac_cv_header_minix_config_h" = x""yes; then :
MINIX=yes
else
MINIX=
@@ -4644,7 +4637,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5
$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; }
-if ${ac_cv_safe_to_define___extensions__+:} false; then :
+if test "${ac_cv_safe_to_define___extensions__+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -4927,7 +4920,7 @@
RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
INSTSONAME="$LDLIBRARY".$SOVERSION
;;
- Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*)
+ Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*)
LDLIBRARY='libpython$(VERSION).so'
BLDLIBRARY='-L. -lpython$(VERSION)'
RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
@@ -4988,7 +4981,7 @@
set dummy ${ac_tool_prefix}ranlib; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
+if test "${ac_cv_prog_RANLIB+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$RANLIB"; then
@@ -5028,7 +5021,7 @@
set dummy ranlib; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$ac_ct_RANLIB"; then
@@ -5082,7 +5075,7 @@
set dummy $ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AR+:} false; then :
+if test "${ac_cv_prog_AR+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$AR"; then
@@ -5132,7 +5125,7 @@
set dummy svnversion; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_SVNVERSION+:} false; then :
+if test "${ac_cv_prog_SVNVERSION+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$SVNVERSION"; then
@@ -5180,7 +5173,7 @@
set dummy hg; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_HAS_HG+:} false; then :
+if test "${ac_cv_prog_HAS_HG+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$HAS_HG"; then
@@ -5279,7 +5272,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
$as_echo_n "checking for a BSD-compatible install... " >&6; }
if test -z "$INSTALL"; then
-if ${ac_cv_path_install+:} false; then :
+if test "${ac_cv_path_install+set}" = set; then :
$as_echo_n "(cached) " >&6
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -5418,6 +5411,12 @@
if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then
WRAP="-fwrapv"
fi
+
+ # Clang also needs -fwrapv
+ if test "$CC" = "clang" ; then
+ WRAP="-fwrapv"
+ fi
+
case $ac_cv_prog_cc_g in
yes)
if test "$Py_DEBUG" = 'true' ; then
@@ -5460,7 +5459,7 @@
$as_echo_n "checking whether $CC accepts -fno-strict-aliasing... " >&6; }
ac_save_cc="$CC"
CC="$CC -fno-strict-aliasing"
- if ${ac_cv_no_strict_aliasing_ok+:} false; then :
+ if test "${ac_cv_no_strict_aliasing_ok+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5650,7 +5649,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -OPT:Olimit=0" >&5
$as_echo_n "checking whether $CC accepts -OPT:Olimit=0... " >&6; }
-if ${ac_cv_opt_olimit_ok+:} false; then :
+if test "${ac_cv_opt_olimit_ok+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_cc="$CC"
@@ -5692,7 +5691,7 @@
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Olimit 1500" >&5
$as_echo_n "checking whether $CC accepts -Olimit 1500... " >&6; }
- if ${ac_cv_olimit_ok+:} false; then :
+ if test "${ac_cv_olimit_ok+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_cc="$CC"
@@ -5770,7 +5769,7 @@
# options before we can check whether -Kpthread improves anything.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads are available without options" >&5
$as_echo_n "checking whether pthreads are available without options... " >&6; }
-if ${ac_cv_pthread_is_default+:} false; then :
+if test "${ac_cv_pthread_is_default+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -5823,7 +5822,7 @@
# function available.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kpthread" >&5
$as_echo_n "checking whether $CC accepts -Kpthread... " >&6; }
-if ${ac_cv_kpthread+:} false; then :
+if test "${ac_cv_kpthread+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_cc="$CC"
@@ -5872,7 +5871,7 @@
# function available.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -Kthread" >&5
$as_echo_n "checking whether $CC accepts -Kthread... " >&6; }
-if ${ac_cv_kthread+:} false; then :
+if test "${ac_cv_kthread+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_cc="$CC"
@@ -5921,7 +5920,7 @@
# function available.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -pthread" >&5
$as_echo_n "checking whether $CC accepts -pthread... " >&6; }
-if ${ac_cv_thread+:} false; then :
+if test "${ac_cv_thread+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_save_cc="$CC"
@@ -6006,7 +6005,7 @@
# checks for header files
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
+if test "${ac_cv_header_stdc+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6145,7 +6144,7 @@
as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh`
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5
$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; }
-if eval \${$as_ac_Header+:} false; then :
+if eval "test \"\${$as_ac_Header+set}\"" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6185,7 +6184,7 @@
if test $ac_header_dirent = dirent.h; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5
$as_echo_n "checking for library containing opendir... " >&6; }
-if ${ac_cv_search_opendir+:} false; then :
+if test "${ac_cv_search_opendir+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_func_search_save_LIBS=$LIBS
@@ -6219,11 +6218,11 @@
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext
- if ${ac_cv_search_opendir+:} false; then :
+ if test "${ac_cv_search_opendir+set}" = set; then :
break
fi
done
-if ${ac_cv_search_opendir+:} false; then :
+if test "${ac_cv_search_opendir+set}" = set; then :
else
ac_cv_search_opendir=no
@@ -6242,7 +6241,7 @@
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5
$as_echo_n "checking for library containing opendir... " >&6; }
-if ${ac_cv_search_opendir+:} false; then :
+if test "${ac_cv_search_opendir+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_func_search_save_LIBS=$LIBS
@@ -6276,11 +6275,11 @@
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext
- if ${ac_cv_search_opendir+:} false; then :
+ if test "${ac_cv_search_opendir+set}" = set; then :
break
fi
done
-if ${ac_cv_search_opendir+:} false; then :
+if test "${ac_cv_search_opendir+set}" = set; then :
else
ac_cv_search_opendir=no
@@ -6300,7 +6299,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether sys/types.h defines makedev" >&5
$as_echo_n "checking whether sys/types.h defines makedev... " >&6; }
-if ${ac_cv_header_sys_types_h_makedev+:} false; then :
+if test "${ac_cv_header_sys_types_h_makedev+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6328,7 +6327,7 @@
if test $ac_cv_header_sys_types_h_makedev = no; then
ac_fn_c_check_header_mongrel "$LINENO" "sys/mkdev.h" "ac_cv_header_sys_mkdev_h" "$ac_includes_default"
-if test "x$ac_cv_header_sys_mkdev_h" = xyes; then :
+if test "x$ac_cv_header_sys_mkdev_h" = x""yes; then :
$as_echo "#define MAJOR_IN_MKDEV 1" >>confdefs.h
@@ -6338,7 +6337,7 @@
if test $ac_cv_header_sys_mkdev_h = no; then
ac_fn_c_check_header_mongrel "$LINENO" "sys/sysmacros.h" "ac_cv_header_sys_sysmacros_h" "$ac_includes_default"
-if test "x$ac_cv_header_sys_sysmacros_h" = xyes; then :
+if test "x$ac_cv_header_sys_sysmacros_h" = x""yes; then :
$as_echo "#define MAJOR_IN_SYSMACROS 1" >>confdefs.h
@@ -6358,7 +6357,7 @@
#endif
"
-if test "x$ac_cv_header_term_h" = xyes; then :
+if test "x$ac_cv_header_term_h" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_TERM_H 1
_ACEOF
@@ -6380,7 +6379,7 @@
#endif
"
-if test "x$ac_cv_header_linux_netlink_h" = xyes; then :
+if test "x$ac_cv_header_linux_netlink_h" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LINUX_NETLINK_H 1
_ACEOF
@@ -6543,7 +6542,7 @@
# Type availability checks
ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default"
-if test "x$ac_cv_type_mode_t" = xyes; then :
+if test "x$ac_cv_type_mode_t" = x""yes; then :
else
@@ -6554,7 +6553,7 @@
fi
ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default"
-if test "x$ac_cv_type_off_t" = xyes; then :
+if test "x$ac_cv_type_off_t" = x""yes; then :
else
@@ -6565,7 +6564,7 @@
fi
ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default"
-if test "x$ac_cv_type_pid_t" = xyes; then :
+if test "x$ac_cv_type_pid_t" = x""yes; then :
else
@@ -6581,7 +6580,7 @@
_ACEOF
ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default"
-if test "x$ac_cv_type_size_t" = xyes; then :
+if test "x$ac_cv_type_size_t" = x""yes; then :
else
@@ -6593,7 +6592,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5
$as_echo_n "checking for uid_t in sys/types.h... " >&6; }
-if ${ac_cv_type_uid_t+:} false; then :
+if test "${ac_cv_type_uid_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6672,7 +6671,7 @@
esac
ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default"
-if test "x$ac_cv_type_ssize_t" = xyes; then :
+if test "x$ac_cv_type_ssize_t" = x""yes; then :
$as_echo "#define HAVE_SSIZE_T 1" >>confdefs.h
@@ -6687,7 +6686,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5
$as_echo_n "checking size of int... " >&6; }
-if ${ac_cv_sizeof_int+:} false; then :
+if test "${ac_cv_sizeof_int+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then :
@@ -6697,7 +6696,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (int)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_int=0
fi
@@ -6720,7 +6719,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5
$as_echo_n "checking size of long... " >&6; }
-if ${ac_cv_sizeof_long+:} false; then :
+if test "${ac_cv_sizeof_long+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then :
@@ -6730,7 +6729,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (long)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_long=0
fi
@@ -6753,7 +6752,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5
$as_echo_n "checking size of void *... " >&6; }
-if ${ac_cv_sizeof_void_p+:} false; then :
+if test "${ac_cv_sizeof_void_p+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then :
@@ -6763,7 +6762,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (void *)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_void_p=0
fi
@@ -6786,7 +6785,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of short" >&5
$as_echo_n "checking size of short... " >&6; }
-if ${ac_cv_sizeof_short+:} false; then :
+if test "${ac_cv_sizeof_short+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (short))" "ac_cv_sizeof_short" "$ac_includes_default"; then :
@@ -6796,7 +6795,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (short)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_short=0
fi
@@ -6819,7 +6818,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of float" >&5
$as_echo_n "checking size of float... " >&6; }
-if ${ac_cv_sizeof_float+:} false; then :
+if test "${ac_cv_sizeof_float+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (float))" "ac_cv_sizeof_float" "$ac_includes_default"; then :
@@ -6829,7 +6828,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (float)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_float=0
fi
@@ -6852,7 +6851,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of double" >&5
$as_echo_n "checking size of double... " >&6; }
-if ${ac_cv_sizeof_double+:} false; then :
+if test "${ac_cv_sizeof_double+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default"; then :
@@ -6862,7 +6861,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (double)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_double=0
fi
@@ -6885,7 +6884,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of fpos_t" >&5
$as_echo_n "checking size of fpos_t... " >&6; }
-if ${ac_cv_sizeof_fpos_t+:} false; then :
+if test "${ac_cv_sizeof_fpos_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (fpos_t))" "ac_cv_sizeof_fpos_t" "$ac_includes_default"; then :
@@ -6895,7 +6894,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (fpos_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_fpos_t=0
fi
@@ -6918,7 +6917,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5
$as_echo_n "checking size of size_t... " >&6; }
-if ${ac_cv_sizeof_size_t+:} false; then :
+if test "${ac_cv_sizeof_size_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default"; then :
@@ -6928,7 +6927,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (size_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_size_t=0
fi
@@ -6951,7 +6950,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pid_t" >&5
$as_echo_n "checking size of pid_t... " >&6; }
-if ${ac_cv_sizeof_pid_t+:} false; then :
+if test "${ac_cv_sizeof_pid_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pid_t))" "ac_cv_sizeof_pid_t" "$ac_includes_default"; then :
@@ -6961,7 +6960,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (pid_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_pid_t=0
fi
@@ -7011,7 +7010,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5
$as_echo_n "checking size of long long... " >&6; }
-if ${ac_cv_sizeof_long_long+:} false; then :
+if test "${ac_cv_sizeof_long_long+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then :
@@ -7021,7 +7020,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (long long)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_long_long=0
fi
@@ -7072,7 +7071,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5
$as_echo_n "checking size of long double... " >&6; }
-if ${ac_cv_sizeof_long_double+:} false; then :
+if test "${ac_cv_sizeof_long_double+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default"; then :
@@ -7082,7 +7081,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (long double)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_long_double=0
fi
@@ -7133,7 +7132,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of _Bool" >&5
$as_echo_n "checking size of _Bool... " >&6; }
-if ${ac_cv_sizeof__Bool+:} false; then :
+if test "${ac_cv_sizeof__Bool+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (_Bool))" "ac_cv_sizeof__Bool" "$ac_includes_default"; then :
@@ -7143,7 +7142,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (_Bool)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof__Bool=0
fi
@@ -7169,7 +7168,7 @@
#include <inttypes.h>
#endif
"
-if test "x$ac_cv_type_uintptr_t" = xyes; then :
+if test "x$ac_cv_type_uintptr_t" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_UINTPTR_T 1
@@ -7181,7 +7180,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of uintptr_t" >&5
$as_echo_n "checking size of uintptr_t... " >&6; }
-if ${ac_cv_sizeof_uintptr_t+:} false; then :
+if test "${ac_cv_sizeof_uintptr_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (uintptr_t))" "ac_cv_sizeof_uintptr_t" "$ac_includes_default"; then :
@@ -7191,7 +7190,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (uintptr_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_uintptr_t=0
fi
@@ -7217,7 +7216,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of off_t" >&5
$as_echo_n "checking size of off_t... " >&6; }
-if ${ac_cv_sizeof_off_t+:} false; then :
+if test "${ac_cv_sizeof_off_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (off_t))" "ac_cv_sizeof_off_t" "
@@ -7232,7 +7231,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (off_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_off_t=0
fi
@@ -7276,7 +7275,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of time_t" >&5
$as_echo_n "checking size of time_t... " >&6; }
-if ${ac_cv_sizeof_time_t+:} false; then :
+if test "${ac_cv_sizeof_time_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (time_t))" "ac_cv_sizeof_time_t" "
@@ -7294,7 +7293,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (time_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_time_t=0
fi
@@ -7350,7 +7349,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of pthread_t" >&5
$as_echo_n "checking size of pthread_t... " >&6; }
-if ${ac_cv_sizeof_pthread_t+:} false; then :
+if test "${ac_cv_sizeof_pthread_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (pthread_t))" "ac_cv_sizeof_pthread_t" "
@@ -7365,7 +7364,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (pthread_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_pthread_t=0
fi
@@ -7877,7 +7876,7 @@
# checks for libraries
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
$as_echo_n "checking for dlopen in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlopen+:} false; then :
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -7911,7 +7910,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
-if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
+if test "x$ac_cv_lib_dl_dlopen" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LIBDL 1
_ACEOF
@@ -7922,7 +7921,7 @@
# Dynamic linking for SunOS/Solaris and SYSV
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
$as_echo_n "checking for shl_load in -ldld... " >&6; }
-if ${ac_cv_lib_dld_shl_load+:} false; then :
+if test "${ac_cv_lib_dld_shl_load+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -7956,7 +7955,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
-if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
+if test "x$ac_cv_lib_dld_shl_load" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LIBDLD 1
_ACEOF
@@ -7970,7 +7969,7 @@
if test "$with_threads" = "yes" -o -z "$with_threads"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing sem_init" >&5
$as_echo_n "checking for library containing sem_init... " >&6; }
-if ${ac_cv_search_sem_init+:} false; then :
+if test "${ac_cv_search_sem_init+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_func_search_save_LIBS=$LIBS
@@ -8004,11 +8003,11 @@
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext
- if ${ac_cv_search_sem_init+:} false; then :
+ if test "${ac_cv_search_sem_init+set}" = set; then :
break
fi
done
-if ${ac_cv_search_sem_init+:} false; then :
+if test "${ac_cv_search_sem_init+set}" = set; then :
else
ac_cv_search_sem_init=no
@@ -8031,7 +8030,7 @@
# check if we need libintl for locale functions
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for textdomain in -lintl" >&5
$as_echo_n "checking for textdomain in -lintl... " >&6; }
-if ${ac_cv_lib_intl_textdomain+:} false; then :
+if test "${ac_cv_lib_intl_textdomain+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8065,7 +8064,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_intl_textdomain" >&5
$as_echo "$ac_cv_lib_intl_textdomain" >&6; }
-if test "x$ac_cv_lib_intl_textdomain" = xyes; then :
+if test "x$ac_cv_lib_intl_textdomain" = x""yes; then :
$as_echo "#define WITH_LIBINTL 1" >>confdefs.h
@@ -8112,7 +8111,7 @@
# BeOS' sockets are stashed in libnet.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for t_open in -lnsl" >&5
$as_echo_n "checking for t_open in -lnsl... " >&6; }
-if ${ac_cv_lib_nsl_t_open+:} false; then :
+if test "${ac_cv_lib_nsl_t_open+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8146,13 +8145,13 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_t_open" >&5
$as_echo "$ac_cv_lib_nsl_t_open" >&6; }
-if test "x$ac_cv_lib_nsl_t_open" = xyes; then :
+if test "x$ac_cv_lib_nsl_t_open" = x""yes; then :
LIBS="-lnsl $LIBS"
fi
# SVR4
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5
$as_echo_n "checking for socket in -lsocket... " >&6; }
-if ${ac_cv_lib_socket_socket+:} false; then :
+if test "${ac_cv_lib_socket_socket+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8186,7 +8185,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5
$as_echo "$ac_cv_lib_socket_socket" >&6; }
-if test "x$ac_cv_lib_socket_socket" = xyes; then :
+if test "x$ac_cv_lib_socket_socket" = x""yes; then :
LIBS="-lsocket $LIBS"
fi
# SVR4 sockets
@@ -8195,7 +8194,7 @@
BeOS*)
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lnet" >&5
$as_echo_n "checking for socket in -lnet... " >&6; }
-if ${ac_cv_lib_net_socket+:} false; then :
+if test "${ac_cv_lib_net_socket+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8229,7 +8228,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_net_socket" >&5
$as_echo "$ac_cv_lib_net_socket" >&6; }
-if test "x$ac_cv_lib_net_socket" = xyes; then :
+if test "x$ac_cv_lib_net_socket" = x""yes; then :
LIBS="-lnet $LIBS"
fi
# BeOS
@@ -8257,7 +8256,7 @@
set dummy ${ac_tool_prefix}pkg-config; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_PKG_CONFIG+:} false; then :
+if test "${ac_cv_path_PKG_CONFIG+set}" = set; then :
$as_echo_n "(cached) " >&6
else
case $PKG_CONFIG in
@@ -8300,7 +8299,7 @@
set dummy pkg-config; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then :
+if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then :
$as_echo_n "(cached) " >&6
else
case $ac_pt_PKG_CONFIG in
@@ -8568,7 +8567,7 @@
$as_echo "#define _REENTRANT 1" >>confdefs.h
ac_fn_c_check_header_mongrel "$LINENO" "cthreads.h" "ac_cv_header_cthreads_h" "$ac_includes_default"
-if test "x$ac_cv_header_cthreads_h" = xyes; then :
+if test "x$ac_cv_header_cthreads_h" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
$as_echo "#define C_THREADS 1" >>confdefs.h
@@ -8581,7 +8580,7 @@
else
ac_fn_c_check_header_mongrel "$LINENO" "mach/cthreads.h" "ac_cv_header_mach_cthreads_h" "$ac_includes_default"
-if test "x$ac_cv_header_mach_cthreads_h" = xyes; then :
+if test "x$ac_cv_header_mach_cthreads_h" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
$as_echo "#define C_THREADS 1" >>confdefs.h
@@ -8643,7 +8642,7 @@
LIBS=$_libs
ac_fn_c_check_func "$LINENO" "pthread_detach" "ac_cv_func_pthread_detach"
-if test "x$ac_cv_func_pthread_detach" = xyes; then :
+if test "x$ac_cv_func_pthread_detach" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
posix_threads=yes
@@ -8651,7 +8650,7 @@
else
ac_fn_c_check_header_mongrel "$LINENO" "atheos/threads.h" "ac_cv_header_atheos_threads_h" "$ac_includes_default"
-if test "x$ac_cv_header_atheos_threads_h" = xyes; then :
+if test "x$ac_cv_header_atheos_threads_h" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
@@ -8661,7 +8660,7 @@
else
ac_fn_c_check_header_mongrel "$LINENO" "kernel/OS.h" "ac_cv_header_kernel_OS_h" "$ac_includes_default"
-if test "x$ac_cv_header_kernel_OS_h" = xyes; then :
+if test "x$ac_cv_header_kernel_OS_h" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
@@ -8672,7 +8671,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreads" >&5
$as_echo_n "checking for pthread_create in -lpthreads... " >&6; }
-if ${ac_cv_lib_pthreads_pthread_create+:} false; then :
+if test "${ac_cv_lib_pthreads_pthread_create+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8706,7 +8705,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_create" >&5
$as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; }
-if test "x$ac_cv_lib_pthreads_pthread_create" = xyes; then :
+if test "x$ac_cv_lib_pthreads_pthread_create" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
posix_threads=yes
@@ -8716,7 +8715,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lc_r" >&5
$as_echo_n "checking for pthread_create in -lc_r... " >&6; }
-if ${ac_cv_lib_c_r_pthread_create+:} false; then :
+if test "${ac_cv_lib_c_r_pthread_create+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8750,7 +8749,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_create" >&5
$as_echo "$ac_cv_lib_c_r_pthread_create" >&6; }
-if test "x$ac_cv_lib_c_r_pthread_create" = xyes; then :
+if test "x$ac_cv_lib_c_r_pthread_create" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
posix_threads=yes
@@ -8760,7 +8759,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __pthread_create_system in -lpthread" >&5
$as_echo_n "checking for __pthread_create_system in -lpthread... " >&6; }
-if ${ac_cv_lib_pthread___pthread_create_system+:} false; then :
+if test "${ac_cv_lib_pthread___pthread_create_system+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8794,7 +8793,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_create_system" >&5
$as_echo "$ac_cv_lib_pthread___pthread_create_system" >&6; }
-if test "x$ac_cv_lib_pthread___pthread_create_system" = xyes; then :
+if test "x$ac_cv_lib_pthread___pthread_create_system" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
posix_threads=yes
@@ -8804,7 +8803,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lcma" >&5
$as_echo_n "checking for pthread_create in -lcma... " >&6; }
-if ${ac_cv_lib_cma_pthread_create+:} false; then :
+if test "${ac_cv_lib_cma_pthread_create+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8838,7 +8837,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cma_pthread_create" >&5
$as_echo "$ac_cv_lib_cma_pthread_create" >&6; }
-if test "x$ac_cv_lib_cma_pthread_create" = xyes; then :
+if test "x$ac_cv_lib_cma_pthread_create" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
posix_threads=yes
@@ -8878,7 +8877,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for usconfig in -lmpc" >&5
$as_echo_n "checking for usconfig in -lmpc... " >&6; }
-if ${ac_cv_lib_mpc_usconfig+:} false; then :
+if test "${ac_cv_lib_mpc_usconfig+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8912,7 +8911,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mpc_usconfig" >&5
$as_echo "$ac_cv_lib_mpc_usconfig" >&6; }
-if test "x$ac_cv_lib_mpc_usconfig" = xyes; then :
+if test "x$ac_cv_lib_mpc_usconfig" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
LIBS="$LIBS -lmpc"
@@ -8924,7 +8923,7 @@
if test "$posix_threads" != "yes"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for thr_create in -lthread" >&5
$as_echo_n "checking for thr_create in -lthread... " >&6; }
-if ${ac_cv_lib_thread_thr_create+:} false; then :
+if test "${ac_cv_lib_thread_thr_create+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -8958,7 +8957,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_thread_thr_create" >&5
$as_echo "$ac_cv_lib_thread_thr_create" >&6; }
-if test "x$ac_cv_lib_thread_thr_create" = xyes; then :
+if test "x$ac_cv_lib_thread_thr_create" = x""yes; then :
$as_echo "#define WITH_THREAD 1" >>confdefs.h
LIBS="$LIBS -lthread"
@@ -8987,7 +8986,7 @@
# Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8.
case $ac_sys_system/$ac_sys_release in
- SunOS/5.6)
+ SunOS/5.6)
$as_echo "#define HAVE_PTHREAD_DESTRUCTOR 1" >>confdefs.h
;;
@@ -8995,19 +8994,15 @@
$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h
;;
- AIX/5)
+ AIX/*)
$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h
;;
- AIX/6)
-$as_echo "#define HAVE_BROKEN_POSIX_SEMAPHORES 1" >>confdefs.h
-
- ;;
esac
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if PTHREAD_SCOPE_SYSTEM is supported" >&5
$as_echo_n "checking if PTHREAD_SCOPE_SYSTEM is supported... " >&6; }
- if ${ac_cv_pthread_system_supported+:} false; then :
+ if test "${ac_cv_pthread_system_supported+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -9050,7 +9045,7 @@
for ac_func in pthread_sigmask
do :
ac_fn_c_check_func "$LINENO" "pthread_sigmask" "ac_cv_func_pthread_sigmask"
-if test "x$ac_cv_func_pthread_sigmask" = xyes; then :
+if test "x$ac_cv_func_pthread_sigmask" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_PTHREAD_SIGMASK 1
_ACEOF
@@ -9440,7 +9435,7 @@
$as_echo "$with_valgrind" >&6; }
if test "$with_valgrind" != no; then
ac_fn_c_check_header_mongrel "$LINENO" "valgrind/valgrind.h" "ac_cv_header_valgrind_valgrind_h" "$ac_includes_default"
-if test "x$ac_cv_header_valgrind_valgrind_h" = xyes; then :
+if test "x$ac_cv_header_valgrind_valgrind_h" = x""yes; then :
$as_echo "#define WITH_VALGRIND 1" >>confdefs.h
@@ -9484,7 +9479,7 @@
for ac_func in dlopen
do :
ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
-if test "x$ac_cv_func_dlopen" = xyes; then :
+if test "x$ac_cv_func_dlopen" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_DLOPEN 1
_ACEOF
@@ -9814,7 +9809,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for flock declaration" >&5
$as_echo_n "checking for flock declaration... " >&6; }
-if ${ac_cv_flock_decl+:} false; then :
+if test "${ac_cv_flock_decl+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -9844,7 +9839,7 @@
for ac_func in flock
do :
ac_fn_c_check_func "$LINENO" "flock" "ac_cv_func_flock"
-if test "x$ac_cv_func_flock" = xyes; then :
+if test "x$ac_cv_func_flock" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_FLOCK 1
_ACEOF
@@ -9852,7 +9847,7 @@
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for flock in -lbsd" >&5
$as_echo_n "checking for flock in -lbsd... " >&6; }
-if ${ac_cv_lib_bsd_flock+:} false; then :
+if test "${ac_cv_lib_bsd_flock+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -9886,7 +9881,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_flock" >&5
$as_echo "$ac_cv_lib_bsd_flock" >&6; }
-if test "x$ac_cv_lib_bsd_flock" = xyes; then :
+if test "x$ac_cv_lib_bsd_flock" = x""yes; then :
$as_echo "#define HAVE_FLOCK 1" >>confdefs.h
@@ -9935,7 +9930,7 @@
set dummy $ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_TRUE+:} false; then :
+if test "${ac_cv_prog_TRUE+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test -n "$TRUE"; then
@@ -9975,7 +9970,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lc" >&5
$as_echo_n "checking for inet_aton in -lc... " >&6; }
-if ${ac_cv_lib_c_inet_aton+:} false; then :
+if test "${ac_cv_lib_c_inet_aton+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10009,12 +10004,12 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_inet_aton" >&5
$as_echo "$ac_cv_lib_c_inet_aton" >&6; }
-if test "x$ac_cv_lib_c_inet_aton" = xyes; then :
+if test "x$ac_cv_lib_c_inet_aton" = x""yes; then :
$ac_cv_prog_TRUE
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton in -lresolv" >&5
$as_echo_n "checking for inet_aton in -lresolv... " >&6; }
-if ${ac_cv_lib_resolv_inet_aton+:} false; then :
+if test "${ac_cv_lib_resolv_inet_aton+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10048,7 +10043,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_resolv_inet_aton" >&5
$as_echo "$ac_cv_lib_resolv_inet_aton" >&6; }
-if test "x$ac_cv_lib_resolv_inet_aton" = xyes; then :
+if test "x$ac_cv_lib_resolv_inet_aton" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LIBRESOLV 1
_ACEOF
@@ -10065,7 +10060,7 @@
# exit Python
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for chflags" >&5
$as_echo_n "checking for chflags... " >&6; }
-if ${ac_cv_have_chflags+:} false; then :
+if test "${ac_cv_have_chflags+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -10073,7 +10068,7 @@
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
-[
+
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char*argv[])
@@ -10082,7 +10077,7 @@
return 1;
return 0;
}
-]
+
_ACEOF
if ac_fn_c_try_run "$LINENO"; then :
ac_cv_have_chflags=yes
@@ -10099,7 +10094,7 @@
$as_echo "$ac_cv_have_chflags" >&6; }
if test "$ac_cv_have_chflags" = cross ; then
ac_fn_c_check_func "$LINENO" "chflags" "ac_cv_func_chflags"
-if test "x$ac_cv_func_chflags" = xyes; then :
+if test "x$ac_cv_func_chflags" = x""yes; then :
ac_cv_have_chflags="yes"
else
ac_cv_have_chflags="no"
@@ -10114,7 +10109,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for lchflags" >&5
$as_echo_n "checking for lchflags... " >&6; }
-if ${ac_cv_have_lchflags+:} false; then :
+if test "${ac_cv_have_lchflags+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -10122,7 +10117,7 @@
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
-[
+
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char*argv[])
@@ -10131,7 +10126,7 @@
return 1;
return 0;
}
-]
+
_ACEOF
if ac_fn_c_try_run "$LINENO"; then :
ac_cv_have_lchflags=yes
@@ -10148,7 +10143,7 @@
$as_echo "$ac_cv_have_lchflags" >&6; }
if test "$ac_cv_have_lchflags" = cross ; then
ac_fn_c_check_func "$LINENO" "lchflags" "ac_cv_func_lchflags"
-if test "x$ac_cv_func_lchflags" = xyes; then :
+if test "x$ac_cv_func_lchflags" = x""yes; then :
ac_cv_have_lchflags="yes"
else
ac_cv_have_lchflags="no"
@@ -10172,7 +10167,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inflateCopy in -lz" >&5
$as_echo_n "checking for inflateCopy in -lz... " >&6; }
-if ${ac_cv_lib_z_inflateCopy+:} false; then :
+if test "${ac_cv_lib_z_inflateCopy+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10206,7 +10201,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_inflateCopy" >&5
$as_echo "$ac_cv_lib_z_inflateCopy" >&6; }
-if test "x$ac_cv_lib_z_inflateCopy" = xyes; then :
+if test "x$ac_cv_lib_z_inflateCopy" = x""yes; then :
$as_echo "#define HAVE_ZLIB_COPY 1" >>confdefs.h
@@ -10349,7 +10344,7 @@
for ac_func in openpty
do :
ac_fn_c_check_func "$LINENO" "openpty" "ac_cv_func_openpty"
-if test "x$ac_cv_func_openpty" = xyes; then :
+if test "x$ac_cv_func_openpty" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_OPENPTY 1
_ACEOF
@@ -10357,7 +10352,7 @@
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lutil" >&5
$as_echo_n "checking for openpty in -lutil... " >&6; }
-if ${ac_cv_lib_util_openpty+:} false; then :
+if test "${ac_cv_lib_util_openpty+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10391,13 +10386,13 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_openpty" >&5
$as_echo "$ac_cv_lib_util_openpty" >&6; }
-if test "x$ac_cv_lib_util_openpty" = xyes; then :
+if test "x$ac_cv_lib_util_openpty" = x""yes; then :
$as_echo "#define HAVE_OPENPTY 1" >>confdefs.h
LIBS="$LIBS -lutil"
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty in -lbsd" >&5
$as_echo_n "checking for openpty in -lbsd... " >&6; }
-if ${ac_cv_lib_bsd_openpty+:} false; then :
+if test "${ac_cv_lib_bsd_openpty+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10431,7 +10426,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_openpty" >&5
$as_echo "$ac_cv_lib_bsd_openpty" >&6; }
-if test "x$ac_cv_lib_bsd_openpty" = xyes; then :
+if test "x$ac_cv_lib_bsd_openpty" = x""yes; then :
$as_echo "#define HAVE_OPENPTY 1" >>confdefs.h
LIBS="$LIBS -lbsd"
fi
@@ -10446,7 +10441,7 @@
for ac_func in forkpty
do :
ac_fn_c_check_func "$LINENO" "forkpty" "ac_cv_func_forkpty"
-if test "x$ac_cv_func_forkpty" = xyes; then :
+if test "x$ac_cv_func_forkpty" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_FORKPTY 1
_ACEOF
@@ -10454,7 +10449,7 @@
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lutil" >&5
$as_echo_n "checking for forkpty in -lutil... " >&6; }
-if ${ac_cv_lib_util_forkpty+:} false; then :
+if test "${ac_cv_lib_util_forkpty+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10488,13 +10483,13 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_util_forkpty" >&5
$as_echo "$ac_cv_lib_util_forkpty" >&6; }
-if test "x$ac_cv_lib_util_forkpty" = xyes; then :
+if test "x$ac_cv_lib_util_forkpty" = x""yes; then :
$as_echo "#define HAVE_FORKPTY 1" >>confdefs.h
LIBS="$LIBS -lutil"
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for forkpty in -lbsd" >&5
$as_echo_n "checking for forkpty in -lbsd... " >&6; }
-if ${ac_cv_lib_bsd_forkpty+:} false; then :
+if test "${ac_cv_lib_bsd_forkpty+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -10528,7 +10523,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_forkpty" >&5
$as_echo "$ac_cv_lib_bsd_forkpty" >&6; }
-if test "x$ac_cv_lib_bsd_forkpty" = xyes; then :
+if test "x$ac_cv_lib_bsd_forkpty" = x""yes; then :
$as_echo "#define HAVE_FORKPTY 1" >>confdefs.h
LIBS="$LIBS -lbsd"
fi
@@ -10545,7 +10540,7 @@
for ac_func in memmove
do :
ac_fn_c_check_func "$LINENO" "memmove" "ac_cv_func_memmove"
-if test "x$ac_cv_func_memmove" = xyes; then :
+if test "x$ac_cv_func_memmove" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_MEMMOVE 1
_ACEOF
@@ -10569,7 +10564,7 @@
ac_fn_c_check_func "$LINENO" "dup2" "ac_cv_func_dup2"
-if test "x$ac_cv_func_dup2" = xyes; then :
+if test "x$ac_cv_func_dup2" = x""yes; then :
$as_echo "#define HAVE_DUP2 1" >>confdefs.h
else
@@ -10582,7 +10577,7 @@
fi
ac_fn_c_check_func "$LINENO" "getcwd" "ac_cv_func_getcwd"
-if test "x$ac_cv_func_getcwd" = xyes; then :
+if test "x$ac_cv_func_getcwd" = x""yes; then :
$as_echo "#define HAVE_GETCWD 1" >>confdefs.h
else
@@ -10595,7 +10590,7 @@
fi
ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup"
-if test "x$ac_cv_func_strdup" = xyes; then :
+if test "x$ac_cv_func_strdup" = x""yes; then :
$as_echo "#define HAVE_STRDUP 1" >>confdefs.h
else
@@ -10611,7 +10606,7 @@
for ac_func in getpgrp
do :
ac_fn_c_check_func "$LINENO" "getpgrp" "ac_cv_func_getpgrp"
-if test "x$ac_cv_func_getpgrp" = xyes; then :
+if test "x$ac_cv_func_getpgrp" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_GETPGRP 1
_ACEOF
@@ -10639,7 +10634,7 @@
for ac_func in setpgrp
do :
ac_fn_c_check_func "$LINENO" "setpgrp" "ac_cv_func_setpgrp"
-if test "x$ac_cv_func_setpgrp" = xyes; then :
+if test "x$ac_cv_func_setpgrp" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_SETPGRP 1
_ACEOF
@@ -10667,7 +10662,7 @@
for ac_func in gettimeofday
do :
ac_fn_c_check_func "$LINENO" "gettimeofday" "ac_cv_func_gettimeofday"
-if test "x$ac_cv_func_gettimeofday" = xyes; then :
+if test "x$ac_cv_func_gettimeofday" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_GETTIMEOFDAY 1
_ACEOF
@@ -10769,7 +10764,7 @@
then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking getaddrinfo bug" >&5
$as_echo_n "checking getaddrinfo bug... " >&6; }
- if ${ac_cv_buggy_getaddrinfo+:} false; then :
+ if test "${ac_cv_buggy_getaddrinfo+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -10898,7 +10893,7 @@
for ac_func in getnameinfo
do :
ac_fn_c_check_func "$LINENO" "getnameinfo" "ac_cv_func_getnameinfo"
-if test "x$ac_cv_func_getnameinfo" = xyes; then :
+if test "x$ac_cv_func_getnameinfo" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_GETNAMEINFO 1
_ACEOF
@@ -10910,7 +10905,7 @@
# checks for structures
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5
$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; }
-if ${ac_cv_header_time+:} false; then :
+if test "${ac_cv_header_time+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -10945,7 +10940,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5
$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; }
-if ${ac_cv_struct_tm+:} false; then :
+if test "${ac_cv_struct_tm+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -10982,7 +10977,7 @@
#include <$ac_cv_struct_tm>
"
-if test "x$ac_cv_member_struct_tm_tm_zone" = xyes; then :
+if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_TM_TM_ZONE 1
@@ -10998,7 +10993,7 @@
else
ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include <time.h>
"
-if test "x$ac_cv_have_decl_tzname" = xyes; then :
+if test "x$ac_cv_have_decl_tzname" = x""yes; then :
ac_have_decl=1
else
ac_have_decl=0
@@ -11010,7 +11005,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5
$as_echo_n "checking for tzname... " >&6; }
-if ${ac_cv_var_tzname+:} false; then :
+if test "${ac_cv_var_tzname+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -11046,7 +11041,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_rdev" "ac_cv_member_struct_stat_st_rdev" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_rdev" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_rdev" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_RDEV 1
@@ -11056,7 +11051,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_blksize" "ac_cv_member_struct_stat_st_blksize" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_blksize" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_blksize" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
@@ -11066,7 +11061,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_flags" "ac_cv_member_struct_stat_st_flags" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_flags" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_flags" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_FLAGS 1
@@ -11076,7 +11071,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_gen" "ac_cv_member_struct_stat_st_gen" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_gen" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_gen" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_GEN 1
@@ -11086,7 +11081,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_birthtime" "ac_cv_member_struct_stat_st_birthtime" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_birthtime" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_birthtime" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
@@ -11096,7 +11091,7 @@
fi
ac_fn_c_check_member "$LINENO" "struct stat" "st_blocks" "ac_cv_member_struct_stat_st_blocks" "$ac_includes_default"
-if test "x$ac_cv_member_struct_stat_st_blocks" = xyes; then :
+if test "x$ac_cv_member_struct_stat_st_blocks" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_STAT_ST_BLOCKS 1
@@ -11118,7 +11113,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for time.h that defines altzone" >&5
$as_echo_n "checking for time.h that defines altzone... " >&6; }
-if ${ac_cv_header_time_altzone+:} false; then :
+if test "${ac_cv_header_time_altzone+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -11182,7 +11177,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for addrinfo" >&5
$as_echo_n "checking for addrinfo... " >&6; }
-if ${ac_cv_struct_addrinfo+:} false; then :
+if test "${ac_cv_struct_addrinfo+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -11214,7 +11209,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sockaddr_storage" >&5
$as_echo_n "checking for sockaddr_storage... " >&6; }
-if ${ac_cv_struct_sockaddr_storage+:} false; then :
+if test "${ac_cv_struct_sockaddr_storage+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -11250,7 +11245,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether char is unsigned" >&5
$as_echo_n "checking whether char is unsigned... " >&6; }
-if ${ac_cv_c_char_unsigned+:} false; then :
+if test "${ac_cv_c_char_unsigned+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -11282,7 +11277,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
-if ${ac_cv_c_const+:} false; then :
+if test "${ac_cv_c_const+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -11570,7 +11565,7 @@
ac_fn_c_check_func "$LINENO" "gethostbyname_r" "ac_cv_func_gethostbyname_r"
-if test "x$ac_cv_func_gethostbyname_r" = xyes; then :
+if test "x$ac_cv_func_gethostbyname_r" = x""yes; then :
$as_echo "#define HAVE_GETHOSTBYNAME_R 1" >>confdefs.h
@@ -11701,7 +11696,7 @@
for ac_func in gethostbyname
do :
ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname"
-if test "x$ac_cv_func_gethostbyname" = xyes; then :
+if test "x$ac_cv_func_gethostbyname" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_GETHOSTBYNAME 1
_ACEOF
@@ -11723,12 +11718,12 @@
# Linux requires this for correct f.p. operations
ac_fn_c_check_func "$LINENO" "__fpu_control" "ac_cv_func___fpu_control"
-if test "x$ac_cv_func___fpu_control" = xyes; then :
+if test "x$ac_cv_func___fpu_control" = x""yes; then :
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __fpu_control in -lieee" >&5
$as_echo_n "checking for __fpu_control in -lieee... " >&6; }
-if ${ac_cv_lib_ieee___fpu_control+:} false; then :
+if test "${ac_cv_lib_ieee___fpu_control+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -11762,7 +11757,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ieee___fpu_control" >&5
$as_echo "$ac_cv_lib_ieee___fpu_control" >&6; }
-if test "x$ac_cv_lib_ieee___fpu_control" = xyes; then :
+if test "x$ac_cv_lib_ieee___fpu_control" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_LIBIEEE 1
_ACEOF
@@ -11857,7 +11852,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are little-endian IEEE 754 binary64" >&5
$as_echo_n "checking whether C doubles are little-endian IEEE 754 binary64... " >&6; }
-if ${ac_cv_little_endian_double+:} false; then :
+if test "${ac_cv_little_endian_double+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -11899,7 +11894,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are big-endian IEEE 754 binary64" >&5
$as_echo_n "checking whether C doubles are big-endian IEEE 754 binary64... " >&6; }
-if ${ac_cv_big_endian_double+:} false; then :
+if test "${ac_cv_big_endian_double+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -11945,7 +11940,7 @@
# conversions work.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C doubles are ARM mixed-endian IEEE 754 binary64" >&5
$as_echo_n "checking whether C doubles are ARM mixed-endian IEEE 754 binary64... " >&6; }
-if ${ac_cv_mixed_endian_double+:} false; then :
+if test "${ac_cv_mixed_endian_double+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -12093,7 +12088,7 @@
# -0. on some architectures.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5
$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; }
-if ${ac_cv_tanh_preserves_zero_sign+:} false; then :
+if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -12161,7 +12156,7 @@
ac_fn_c_check_decl "$LINENO" "isinf" "ac_cv_have_decl_isinf" "#include <math.h>
"
-if test "x$ac_cv_have_decl_isinf" = xyes; then :
+if test "x$ac_cv_have_decl_isinf" = x""yes; then :
ac_have_decl=1
else
ac_have_decl=0
@@ -12172,7 +12167,7 @@
_ACEOF
ac_fn_c_check_decl "$LINENO" "isnan" "ac_cv_have_decl_isnan" "#include <math.h>
"
-if test "x$ac_cv_have_decl_isnan" = xyes; then :
+if test "x$ac_cv_have_decl_isnan" = x""yes; then :
ac_have_decl=1
else
ac_have_decl=0
@@ -12183,7 +12178,7 @@
_ACEOF
ac_fn_c_check_decl "$LINENO" "isfinite" "ac_cv_have_decl_isfinite" "#include <math.h>
"
-if test "x$ac_cv_have_decl_isfinite" = xyes; then :
+if test "x$ac_cv_have_decl_isfinite" = x""yes; then :
ac_have_decl=1
else
ac_have_decl=0
@@ -12203,7 +12198,7 @@
# sem_open results in a 'Signal 12' error.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether POSIX semaphores are enabled" >&5
$as_echo_n "checking whether POSIX semaphores are enabled... " >&6; }
-if ${ac_cv_posix_semaphores_enabled+:} false; then :
+if test "${ac_cv_posix_semaphores_enabled+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -12254,7 +12249,7 @@
# Multiprocessing check for broken sem_getvalue
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken sem_getvalue" >&5
$as_echo_n "checking for broken sem_getvalue... " >&6; }
-if ${ac_cv_broken_sem_getvalue+:} false; then :
+if test "${ac_cv_broken_sem_getvalue+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -12319,7 +12314,7 @@
15|30)
;;
*)
- as_fn_error $? "bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" "$LINENO" 5 ;;
+ as_fn_error $? "bad value $enable_big_digits for --enable-big-digits; value should be 15 or 30" "$LINENO" 5 ;;
esac
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_big_digits" >&5
$as_echo "$enable_big_digits" >&6; }
@@ -12337,7 +12332,7 @@
# check for wchar.h
ac_fn_c_check_header_mongrel "$LINENO" "wchar.h" "ac_cv_header_wchar_h" "$ac_includes_default"
-if test "x$ac_cv_header_wchar_h" = xyes; then :
+if test "x$ac_cv_header_wchar_h" = x""yes; then :
$as_echo "#define HAVE_WCHAR_H 1" >>confdefs.h
@@ -12360,7 +12355,7 @@
# This bug is HP SR number 8606223364.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of wchar_t" >&5
$as_echo_n "checking size of wchar_t... " >&6; }
-if ${ac_cv_sizeof_wchar_t+:} false; then :
+if test "${ac_cv_sizeof_wchar_t+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (wchar_t))" "ac_cv_sizeof_wchar_t" "#include <wchar.h>
@@ -12371,7 +12366,7 @@
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "cannot compute sizeof (wchar_t)
-See \`config.log' for more details" "$LINENO" 5; }
+See \`config.log' for more details" "$LINENO" 5 ; }
else
ac_cv_sizeof_wchar_t=0
fi
@@ -12426,7 +12421,7 @@
# check whether wchar_t is signed or not
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether wchar_t is signed" >&5
$as_echo_n "checking whether wchar_t is signed... " >&6; }
- if ${ac_cv_wchar_t_signed+:} false; then :
+ if test "${ac_cv_wchar_t_signed+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -12490,7 +12485,7 @@
$as_echo "#define Py_UNICODE_SIZE 4" >>confdefs.h
;;
-*) as_fn_error $? "invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." "$LINENO" 5 ;;
+*) as_fn_error $? "invalid value for --enable-unicode. Use either ucs2 or ucs4 (lowercase)." "$LINENO" 5 ;;
esac
@@ -12537,7 +12532,7 @@
# check for endianness
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
+if test "${ac_cv_c_bigendian+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_cv_c_bigendian=unknown
@@ -12756,7 +12751,7 @@
;; #(
*)
as_fn_error $? "unknown endianness
- presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
+ presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
esac
@@ -12764,7 +12759,7 @@
# or fills with zeros (like the Cray J90, according to Tim Peters).
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether right shift extends the sign bit" >&5
$as_echo_n "checking whether right shift extends the sign bit... " >&6; }
-if ${ac_cv_rshift_extends_sign+:} false; then :
+if test "${ac_cv_rshift_extends_sign+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -12803,7 +12798,7 @@
# check for getc_unlocked and related locking functions
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getc_unlocked() and friends" >&5
$as_echo_n "checking for getc_unlocked() and friends... " >&6; }
-if ${ac_cv_have_getc_unlocked+:} false; then :
+if test "${ac_cv_have_getc_unlocked+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -12901,7 +12896,7 @@
# check for readline 2.1
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_callback_handler_install in -lreadline" >&5
$as_echo_n "checking for rl_callback_handler_install in -lreadline... " >&6; }
-if ${ac_cv_lib_readline_rl_callback_handler_install+:} false; then :
+if test "${ac_cv_lib_readline_rl_callback_handler_install+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -12935,7 +12930,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_callback_handler_install" >&5
$as_echo "$ac_cv_lib_readline_rl_callback_handler_install" >&6; }
-if test "x$ac_cv_lib_readline_rl_callback_handler_install" = xyes; then :
+if test "x$ac_cv_lib_readline_rl_callback_handler_install" = x""yes; then :
$as_echo "#define HAVE_RL_CALLBACK 1" >>confdefs.h
@@ -12987,7 +12982,7 @@
# check for readline 4.0
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_pre_input_hook in -lreadline" >&5
$as_echo_n "checking for rl_pre_input_hook in -lreadline... " >&6; }
-if ${ac_cv_lib_readline_rl_pre_input_hook+:} false; then :
+if test "${ac_cv_lib_readline_rl_pre_input_hook+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -13021,7 +13016,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_pre_input_hook" >&5
$as_echo "$ac_cv_lib_readline_rl_pre_input_hook" >&6; }
-if test "x$ac_cv_lib_readline_rl_pre_input_hook" = xyes; then :
+if test "x$ac_cv_lib_readline_rl_pre_input_hook" = x""yes; then :
$as_echo "#define HAVE_RL_PRE_INPUT_HOOK 1" >>confdefs.h
@@ -13031,7 +13026,7 @@
# also in 4.0
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_display_matches_hook in -lreadline" >&5
$as_echo_n "checking for rl_completion_display_matches_hook in -lreadline... " >&6; }
-if ${ac_cv_lib_readline_rl_completion_display_matches_hook+:} false; then :
+if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -13065,7 +13060,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5
$as_echo "$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; }
-if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = xyes; then :
+if test "x$ac_cv_lib_readline_rl_completion_display_matches_hook" = x""yes; then :
$as_echo "#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1" >>confdefs.h
@@ -13075,7 +13070,7 @@
# check for readline 4.2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rl_completion_matches in -lreadline" >&5
$as_echo_n "checking for rl_completion_matches in -lreadline... " >&6; }
-if ${ac_cv_lib_readline_rl_completion_matches+:} false; then :
+if test "${ac_cv_lib_readline_rl_completion_matches+set}" = set; then :
$as_echo_n "(cached) " >&6
else
ac_check_lib_save_LIBS=$LIBS
@@ -13109,7 +13104,7 @@
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_rl_completion_matches" >&5
$as_echo "$ac_cv_lib_readline_rl_completion_matches" >&6; }
-if test "x$ac_cv_lib_readline_rl_completion_matches" = xyes; then :
+if test "x$ac_cv_lib_readline_rl_completion_matches" = x""yes; then :
$as_echo "#define HAVE_RL_COMPLETION_MATCHES 1" >>confdefs.h
@@ -13150,7 +13145,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken nice()" >&5
$as_echo_n "checking for broken nice()... " >&6; }
-if ${ac_cv_broken_nice+:} false; then :
+if test "${ac_cv_broken_nice+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -13191,7 +13186,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for broken poll()" >&5
$as_echo_n "checking for broken poll()... " >&6; }
-if ${ac_cv_broken_poll+:} false; then :
+if test "${ac_cv_broken_poll+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -13246,7 +13241,7 @@
#include <$ac_cv_struct_tm>
"
-if test "x$ac_cv_member_struct_tm_tm_zone" = xyes; then :
+if test "x$ac_cv_member_struct_tm_tm_zone" = x""yes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STRUCT_TM_TM_ZONE 1
@@ -13262,7 +13257,7 @@
else
ac_fn_c_check_decl "$LINENO" "tzname" "ac_cv_have_decl_tzname" "#include <time.h>
"
-if test "x$ac_cv_have_decl_tzname" = xyes; then :
+if test "x$ac_cv_have_decl_tzname" = x""yes; then :
ac_have_decl=1
else
ac_have_decl=0
@@ -13274,7 +13269,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tzname" >&5
$as_echo_n "checking for tzname... " >&6; }
-if ${ac_cv_var_tzname+:} false; then :
+if test "${ac_cv_var_tzname+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -13313,7 +13308,7 @@
# check tzset(3) exists and works like we expect it to
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working tzset()" >&5
$as_echo_n "checking for working tzset()... " >&6; }
-if ${ac_cv_working_tzset+:} false; then :
+if test "${ac_cv_working_tzset+set}" = set; then :
$as_echo_n "(cached) " >&6
else
@@ -13410,7 +13405,7 @@
# Look for subsecond timestamps in struct stat
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec in struct stat" >&5
$as_echo_n "checking for tv_nsec in struct stat... " >&6; }
-if ${ac_cv_stat_tv_nsec+:} false; then :
+if test "${ac_cv_stat_tv_nsec+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -13447,7 +13442,7 @@
# Look for BSD style subsecond timestamps in struct stat
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tv_nsec2 in struct stat" >&5
$as_echo_n "checking for tv_nsec2 in struct stat... " >&6; }
-if ${ac_cv_stat_tv_nsec2+:} false; then :
+if test "${ac_cv_stat_tv_nsec2+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -13484,7 +13479,7 @@
# On HP/UX 11.0, mvwdelch is a block with a return statement
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether mvwdelch is an expression" >&5
$as_echo_n "checking whether mvwdelch is an expression... " >&6; }
-if ${ac_cv_mvwdelch_is_expression+:} false; then :
+if test "${ac_cv_mvwdelch_is_expression+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -13521,7 +13516,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether WINDOW has _flags" >&5
$as_echo_n "checking whether WINDOW has _flags... " >&6; }
-if ${ac_cv_window_has_flags+:} false; then :
+if test "${ac_cv_window_has_flags+set}" = set; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -13669,7 +13664,7 @@
then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %lld and %llu printf() format support" >&5
$as_echo_n "checking for %lld and %llu printf() format support... " >&6; }
- if ${ac_cv_have_long_long_format+:} false; then :
+ if test "${ac_cv_have_long_long_format+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -13740,7 +13735,7 @@
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %zd printf() format support" >&5
$as_echo_n "checking for %zd printf() format support... " >&6; }
-if ${ac_cv_have_size_t_format+:} false; then :
+if test "${ac_cv_have_size_t_format+set}" = set; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
@@ -13813,7 +13808,7 @@
#endif
"
-if test "x$ac_cv_type_socklen_t" = xyes; then :
+if test "x$ac_cv_type_socklen_t" = x""yes; then :
else
@@ -13918,21 +13913,10 @@
:end' >>confcache
if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
if test -w "$cache_file"; then
- if test "x$cache_file" != "x/dev/null"; then
+ test "x$cache_file" != "x/dev/null" &&
{ $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
$as_echo "$as_me: updating cache $cache_file" >&6;}
- if test ! -f "$cache_file" || test -h "$cache_file"; then
- cat confcache >"$cache_file"
- else
- case $cache_file in #(
- */* | ?:*)
- mv -f confcache "$cache_file"$$ &&
- mv -f "$cache_file"$$ "$cache_file" ;; #(
- *)
- mv -f confcache "$cache_file" ;;
- esac
- fi
- fi
+ cat confcache >$cache_file
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
@@ -13965,7 +13949,7 @@
-: "${CONFIG_STATUS=./config.status}"
+: ${CONFIG_STATUS=./config.status}
ac_write_fail=0
ac_clean_files_save=$ac_clean_files
ac_clean_files="$ac_clean_files $CONFIG_STATUS"
@@ -14066,7 +14050,6 @@
IFS=" "" $as_nl"
# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
case $0 in #((
*[\\/]* ) as_myself=$0 ;;
*) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -14374,7 +14357,7 @@
# values after options handling.
ac_log="
This file was extended by python $as_me 2.7, which was
-generated by GNU Autoconf 2.68. Invocation command line was
+generated by GNU Autoconf 2.67. Invocation command line was
CONFIG_FILES = $CONFIG_FILES
CONFIG_HEADERS = $CONFIG_HEADERS
@@ -14436,7 +14419,7 @@
ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
ac_cs_version="\\
python config.status 2.7
-configured by $0, generated by GNU Autoconf 2.68,
+configured by $0, generated by GNU Autoconf 2.67,
with options \\"\$ac_cs_config\\"
Copyright (C) 2010 Free Software Foundation, Inc.
@@ -14568,7 +14551,7 @@
"Misc/python.pc") CONFIG_FILES="$CONFIG_FILES Misc/python.pc" ;;
"Modules/ld_so_aix") CONFIG_FILES="$CONFIG_FILES Modules/ld_so_aix" ;;
- *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+ *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;;
esac
done
@@ -14590,10 +14573,9 @@
# after its creation but before its name has been assigned to `$tmp'.
$debug ||
{
- tmp= ac_tmp=
+ tmp=
trap 'exit_status=$?
- : "${ac_tmp:=$tmp}"
- { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+ { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
' 0
trap 'as_fn_exit 1' 1 2 13 15
}
@@ -14601,13 +14583,12 @@
{
tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
- test -d "$tmp"
+ test -n "$tmp" && test -d "$tmp"
} ||
{
tmp=./conf$$-$RANDOM
(umask 077 && mkdir "$tmp")
} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
# Set up the scripts for CONFIG_FILES section.
# No need to generate them if there are no CONFIG_FILES.
@@ -14629,7 +14610,7 @@
ac_cs_awk_cr=$ac_cr
fi
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+echo 'BEGIN {' >"$tmp/subs1.awk" &&
_ACEOF
@@ -14657,7 +14638,7 @@
rm -f conf$$subs.sh
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
_ACEOF
sed -n '
h
@@ -14705,7 +14686,7 @@
rm -f conf$$subs.awk
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+cat >>"\$tmp/subs1.awk" <<_ACAWK &&
for (key in S) S_is_set[key] = 1
FS = ""
@@ -14737,7 +14718,7 @@
sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
else
cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
|| as_fn_error $? "could not setup config files machinery" "$LINENO" 5
_ACEOF
@@ -14771,7 +14752,7 @@
# No need to generate them if there are no CONFIG_HEADERS.
# This happens for instance with `./config.status Makefile'.
if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
+cat >"$tmp/defines.awk" <<\_ACAWK ||
BEGIN {
_ACEOF
@@ -14783,8 +14764,8 @@
# handling of long lines.
ac_delim='%!_!# '
for ac_last_try in false false :; do
- ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
- if test -z "$ac_tt"; then
+ ac_t=`sed -n "/$ac_delim/p" confdefs.h`
+ if test -z "$ac_t"; then
break
elif $ac_last_try; then
as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
@@ -14885,7 +14866,7 @@
esac
case $ac_mode$ac_tag in
:[FHL]*:*);;
- :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+ :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;;
:[FH]-) ac_tag=-:-;;
:[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
esac
@@ -14904,7 +14885,7 @@
for ac_f
do
case $ac_f in
- -) ac_f="$ac_tmp/stdin";;
+ -) ac_f="$tmp/stdin";;
*) # Look for the file first in the build tree, then in the source tree
# (if the path is not absolute). The absolute path cannot be DOS-style,
# because $ac_f cannot contain `:'.
@@ -14913,7 +14894,7 @@
[\\/$]*) false;;
*) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
esac ||
- as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+ as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;;
esac
case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
as_fn_append ac_file_inputs " '$ac_f'"
@@ -14939,8 +14920,8 @@
esac
case $ac_tag in
- *:-:* | *:-) cat >"$ac_tmp/stdin" \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+ *:-:* | *:-) cat >"$tmp/stdin" \
+ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
esac
;;
esac
@@ -15070,22 +15051,21 @@
s&@INSTALL@&$ac_INSTALL&;t t
$ac_datarootdir_hack
"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
- >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \
+ || as_fn_error $? "could not create $ac_file" "$LINENO" 5
test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
- { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
- { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \
- "$ac_tmp/out"`; test -z "$ac_out"; } &&
+ { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+ { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
which seems to be undefined. Please make sure it is defined" >&5
$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
which seems to be undefined. Please make sure it is defined" >&2;}
- rm -f "$ac_tmp/stdin"
+ rm -f "$tmp/stdin"
case $ac_file in
- -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
- *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+ -) cat "$tmp/out" && rm -f "$tmp/out";;
+ *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
esac \
|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
;;
@@ -15096,20 +15076,20 @@
if test x"$ac_file" != x-; then
{
$as_echo "/* $configure_input */" \
- && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
- } >"$ac_tmp/config.h" \
+ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
+ } >"$tmp/config.h" \
|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
- if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
+ if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
$as_echo "$as_me: $ac_file is unchanged" >&6;}
else
rm -f "$ac_file"
- mv "$ac_tmp/config.h" "$ac_file" \
+ mv "$tmp/config.h" "$ac_file" \
|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
fi
else
$as_echo "/* $configure_input */" \
- && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
+ && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
|| as_fn_error $? "could not create -" "$LINENO" 5
fi
;;
diff --git a/configure.in b/configure.in
index ea106b5..9d7bfa6 100644
--- a/configure.in
+++ b/configure.in
@@ -293,6 +293,7 @@
MACHDEP="$ac_md_system$ac_md_release"
case $MACHDEP in
+ linux*) MACHDEP="linux2";;
cygwin*) MACHDEP="cygwin";;
darwin*) MACHDEP="darwin";;
atheos*) MACHDEP="atheos";;
@@ -317,14 +318,14 @@
# Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish.
# In addition, Stefan Krah confirms that issue #1244610 exists through
# OpenBSD 4.6, but is fixed in 4.7.
- OpenBSD/2.* | OpenBSD/3.@<:@0123456789@:>@ | OpenBSD/4.@<:@0123456@:>@)
+ OpenBSD/2.* | OpenBSD/3.* | OpenBSD/4.@<:@0123456@:>@)
define_xopen_source=no
# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
# also defined. This can be overridden by defining _BSD_SOURCE
# As this has a different meaning on Linux, only define it on OpenBSD
AC_DEFINE(_BSD_SOURCE, 1, [Define on OpenBSD to activate all library features])
;;
- OpenBSD/4.@<:@789@:>@)
+ OpenBSD/*)
# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is
# also defined. This can be overridden by defining _BSD_SOURCE
# As this has a different meaning on Linux, only define it on OpenBSD
@@ -778,7 +779,7 @@
RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
INSTSONAME="$LDLIBRARY".$SOVERSION
;;
- Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*)
+ Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*)
LDLIBRARY='libpython$(VERSION).so'
BLDLIBRARY='-L. -lpython$(VERSION)'
RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
@@ -931,6 +932,12 @@
if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then
WRAP="-fwrapv"
fi
+
+ # Clang also needs -fwrapv
+ if test "$CC" = "clang" ; then
+ WRAP="-fwrapv"
+ fi
+
case $ac_cv_prog_cc_g in
yes)
if test "$Py_DEBUG" = 'true' ; then
@@ -2359,18 +2366,15 @@
# Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8.
case $ac_sys_system/$ac_sys_release in
- SunOS/5.6) AC_DEFINE(HAVE_PTHREAD_DESTRUCTOR, 1,
+ SunOS/5.6) AC_DEFINE(HAVE_PTHREAD_DESTRUCTOR, 1,
[Defined for Solaris 2.6 bug in pthread header.])
;;
SunOS/5.8) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1,
[Define if the Posix semaphores do not work on your system])
;;
- AIX/5) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1,
+ AIX/*) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1,
[Define if the Posix semaphores do not work on your system])
;;
- AIX/6) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1,
- Define if the Posix semaphores do not work on your system)
- ;;
esac
AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported)
@@ -2839,7 +2843,7 @@
# On Tru64, chflags seems to be present, but calling it will
# exit Python
AC_CACHE_CHECK([for chflags], [ac_cv_have_chflags], [dnl
-AC_RUN_IFELSE([AC_LANG_SOURCE([[[
+AC_RUN_IFELSE([AC_LANG_SOURCE([[
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char*argv[])
@@ -2848,7 +2852,7 @@
return 1;
return 0;
}
-]]])],
+]])],
[ac_cv_have_chflags=yes],
[ac_cv_have_chflags=no],
[ac_cv_have_chflags=cross])
@@ -2857,11 +2861,11 @@
AC_CHECK_FUNC([chflags], [ac_cv_have_chflags="yes"], [ac_cv_have_chflags="no"])
fi
if test "$ac_cv_have_chflags" = yes ; then
- AC_DEFINE(HAVE_CHFLAGS, 1, [Define to 1 if you have the `chflags' function.])
+ AC_DEFINE(HAVE_CHFLAGS, 1, [Define to 1 if you have the 'chflags' function.])
fi
AC_CACHE_CHECK([for lchflags], [ac_cv_have_lchflags], [dnl
-AC_RUN_IFELSE([AC_LANG_SOURCE([[[
+AC_RUN_IFELSE([AC_LANG_SOURCE([[
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char*argv[])
@@ -2870,13 +2874,13 @@
return 1;
return 0;
}
-]]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross])
+]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross])
])
if test "$ac_cv_have_lchflags" = cross ; then
AC_CHECK_FUNC([lchflags], [ac_cv_have_lchflags="yes"], [ac_cv_have_lchflags="no"])
fi
if test "$ac_cv_have_lchflags" = yes ; then
- AC_DEFINE(HAVE_LCHFLAGS, 1, [Define to 1 if you have the `lchflags' function.])
+ AC_DEFINE(HAVE_LCHFLAGS, 1, [Define to 1 if you have the 'lchflags' function.])
fi
dnl Check if system zlib has *Copy() functions
diff --git a/pyconfig.h.in b/pyconfig.h.in
index 65ad7ac..9d340f6 100644
--- a/pyconfig.h.in
+++ b/pyconfig.h.in
@@ -100,7 +100,7 @@
/* Define this if you have the type _Bool. */
#undef HAVE_C99_BOOL
-/* Define to 1 if you have the `chflags' function. */
+/* Define to 1 if you have the 'chflags' function. */
#undef HAVE_CHFLAGS
/* Define to 1 if you have the `chown' function. */
@@ -391,7 +391,7 @@
Solaris and Linux, the necessary defines are already defined.) */
#undef HAVE_LARGEFILE_SUPPORT
-/* Define to 1 if you have the `lchflags' function. */
+/* Define to 1 if you have the 'lchflags' function. */
#undef HAVE_LCHFLAGS
/* Define to 1 if you have the `lchmod' function. */
@@ -1137,6 +1137,9 @@
/* This must be defined on some systems to enable large file support. */
#undef _LARGEFILE_SOURCE
+/* This must be defined on AIX systems to enable large file support. */
+#undef _LARGE_FILES
+
/* Define to 1 if on MINIX. */
#undef _MINIX