From: DongHun Kwak Date: Mon, 16 Oct 2017 11:05:22 +0000 (+0900) Subject: Imported Upstream version 3.6.3 X-Git-Tag: upstream/3.6.3^0 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=refs%2Fchanges%2F06%2F155906%2F1;p=platform%2Fupstream%2Fpython3.git Imported Upstream version 3.6.3 Change-Id: I517f0592d098f9860b48c8a5acf3d9d7a83fe3d0 Signed-off-by: DongHun Kwak --- diff --git a/Doc/Makefile b/Doc/Makefile index ae59f32..307d1e0 100644 --- a/Doc/Makefile +++ b/Doc/Makefile @@ -5,7 +5,9 @@ # You can set these variables from the command line. PYTHON = python3 -SPHINXBUILD = sphinx-build +VENVDIR = ./venv +SPHINXBUILD = PATH=$(VENVDIR)/bin:$$PATH sphinx-build +BLURB = PATH=$(VENVDIR)/bin:$$PATH blurb PAPER = SOURCES = DISTVERSION = $(shell $(PYTHON) tools/extensions/patchlevel.py) @@ -38,6 +40,20 @@ help: @echo " serve to serve the documentation on the localhost (8000)" build: + -mkdir -p build +# Look first for a Misc/NEWS file (building from a source release tarball +# or old repo) and use that, otherwise look for a Misc/NEWS.d directory +# (building from a newer repo) and use blurb to generate the NEWS file. + @if [ -f ../Misc/NEWS ] ; then \ + echo "Using existing Misc/NEWS file"; \ + cp ../Misc/NEWS build/NEWS; \ + elif [ -d ../Misc/NEWS.d ]; then \ + echo "Building NEWS from Misc/NEWS.d with blurb"; \ + $(BLURB) merge -f build/NEWS; \ + else \ + echo "Neither Misc/NEWS.d nor Misc/NEWS found; cannot build docs"; \ + exit 1; \ + fi $(SPHINXBUILD) $(ALLSPHINXOPTS) @echo @@ -103,11 +119,12 @@ htmlview: html $(PYTHON) -c "import webbrowser; webbrowser.open('build/html/index.html')" clean: - -rm -rf build/* venv/* + -rm -rf build/* $(VENVDIR)/* venv: - $(PYTHON) -m venv venv - ./venv/bin/python3 -m pip install -U Sphinx + $(PYTHON) -m venv $(VENVDIR) + $(VENVDIR)/bin/python3 -m pip install -U Sphinx blurb + @echo "The venv has been created in the $(VENVDIR) directory" dist: rm -rf dist @@ -153,7 +170,7 @@ dist: cp -pPR build/epub/Python.epub dist/python-$(DISTVERSION)-docs.epub check: - $(PYTHON) tools/rstlint.py -i tools -i venv -i README.rst + $(PYTHON) tools/rstlint.py -i tools -i $(VENVDIR) -i README.rst serve: ../Tools/scripts/serve.py build/html @@ -167,12 +184,12 @@ serve: # for development releases: always build autobuild-dev: - make dist SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A versionswitcher=1' + make dist SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A switchers=1' -make suspicious # for quick rebuilds (HTML only) autobuild-dev-html: - make html SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A versionswitcher=1' + make html SPHINXOPTS='$(SPHINXOPTS) -Ea -A daily=1 -A switchers=1' # for stable releases: only build if not in pre-release stage (alpha, beta) # release candidate downloads are okay, since the stable tree can be in that stage diff --git a/Doc/README.rst b/Doc/README.rst index dcd3d6e..a29d1f3 100644 --- a/Doc/README.rst +++ b/Doc/README.rst @@ -7,45 +7,53 @@ available `_. Documentation on authoring Python documentation, including information about both style and markup, is available in the "`Documenting Python -`_" chapter of the +`_" chapter of the developers guide. Building the docs ================= -You need to have `Sphinx `_ installed; it is the toolset -used to build the docs. It is not included in this tree, but maintained -separately and `available from PyPI `_. +The documentation is built with several tools which are not included in this +tree but are maintained separately and are available from +`PyPI `_. + +* `Sphinx `_ +* `blurb `_ + +The easiest way to install these tools is to create a virtual environment and +install the tools into there. Using make ---------- -A Makefile has been prepared so that on Unix, provided you have installed -Sphinx, you can just run :: +To get started on UNIX, you can create a virtual environment with the command :: - make html + make venv -to build the HTML output files. - -On Windows, we try to emulate the Makefile as closely as possible with a -``make.bat`` file. +That will install all the tools necessary to build the documentation. Assuming +the virtual environment was created in the ``env`` directory (the default; +configurable with the VENVDIR variable), you can run the following command to +build the HTML output files:: -To use a Python interpreter that's not called ``python``, use the standard -way to set Makefile variables, using e.g. :: + make html - make html PYTHON=python3 +By default, if the virtual environment is not created, the Makefile will +look for instances of sphinxbuild and blurb installed on your process PATH +(configurable with the SPHINXBUILD and BLURB variables). -On Windows, set the PYTHON environment variable instead. - -To use a specific sphinx-build (something other than ``sphinx-build``), set -the SPHINXBUILD variable. +On Windows, we try to emulate the Makefile as closely as possible with a +``make.bat`` file. If you need to specify the Python interpreter to use, +set the PYTHON environment variable instead. Available make targets are: * "clean", which removes all build files. +* "venv", which creates a virtual environment with all necessary tools + installed. + * "html", which builds standalone HTML files for offline viewing. * "htmlview", which re-uses the "html" builder, but then opens the main page @@ -96,7 +104,7 @@ Available make targets are: Without make ------------ -Install the Sphinx package and its dependencies from PyPI. +First, install the tool dependencies from PyPI. Then, from the ``Doc`` directory, run :: @@ -109,11 +117,10 @@ see the make targets above). Contributing ============ -Bugs in the content should be reported to the +Bugs in the content should be reported to the `Python bug tracker `_. -Bugs in the toolset should be reported in the -`Sphinx bug tracker `_. +Bugs in the toolset should be reported to the tools themselves. You can also send a mail to the Python Documentation Team at docs@python.org, and we will process your request as soon as possible. diff --git a/Doc/bugs.rst b/Doc/bugs.rst index 1b0a5a9..bc1d10f 100644 --- a/Doc/bugs.rst +++ b/Doc/bugs.rst @@ -88,5 +88,5 @@ the `core-mentorship mailing list`_ is a friendly place to get answers to any and all questions pertaining to the process of fixing issues in Python. .. _Documentation bugs: https://bugs.python.org/issue?@filter=status&@filter=components&components=4&status=1&@columns=id,activity,title,status&@sort=-activity -.. _Python Developer's Guide: https://docs.python.org/devguide/ +.. _Python Developer's Guide: https://devguide.python.org/ .. _core-mentorship mailing list: https://mail.python.org/mailman/listinfo/core-mentorship/ diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst index c080f31..675f6f2 100644 --- a/Doc/c-api/structures.rst +++ b/Doc/c-api/structures.rst @@ -294,3 +294,43 @@ definition with the same method name. read-only access. Using :c:macro:`T_STRING` for :attr:`type` implies :c:macro:`READONLY`. Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` members can be deleted. (They are set to *NULL*). + + +.. c:type:: PyGetSetDef + + Structure to define property-like access for a type. See also description of + the :c:member:`PyTypeObject.tp_getset` slot. + + +-------------+------------------+-----------------------------------+ + | Field | C Type | Meaning | + +=============+==================+===================================+ + | name | char \* | attribute name | + +-------------+------------------+-----------------------------------+ + | get | getter | C Function to get the attribute | + +-------------+------------------+-----------------------------------+ + | set | setter | optional C function to set or | + | | | delete the attribute, if omitted | + | | | the attribute is readonly | + +-------------+------------------+-----------------------------------+ + | doc | char \* | optional docstring | + +-------------+------------------+-----------------------------------+ + | closure | void \* | optional function pointer, | + | | | providing additional data for | + | | | getter and setter | + +-------------+------------------+-----------------------------------+ + + The ``get`` function takes one :c:type:`PyObject\*` parameter (the + instance) and a function pointer (the associated ``closure``):: + + typedef PyObject *(*getter)(PyObject *, void *); + + It should return a new reference on success or *NULL* with a set exception + on failure. + + ``set`` functions take two :c:type:`PyObject\*` parameters (the instance and + the value to be set) and a function pointer (the associated ``closure``):: + + typedef int (*setter)(PyObject *, PyObject *, void *); + + In case the attribute should be deleted the second parameter is *NULL*. + Should return ``0`` on success or ``-1`` with a set exception on failure. diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index ac6fd0b..0b4577f 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -719,21 +719,6 @@ type objects) *must* have the :attr:`ob_size` field. This field is not inherited by subtypes (computed attributes are inherited through a different mechanism). - .. XXX belongs elsewhere - - Docs for PyGetSetDef:: - - typedef PyObject *(*getter)(PyObject *, void *); - typedef int (*setter)(PyObject *, PyObject *, void *); - - typedef struct PyGetSetDef { - char *name; /* attribute name */ - getter get; /* C function to get the attribute */ - setter set; /* C function to set or delete the attribute */ - char *doc; /* optional doc string */ - void *closure; /* optional additional data for getter and setter */ - } PyGetSetDef; - .. c:member:: PyTypeObject* PyTypeObject.tp_base diff --git a/Doc/conf.py b/Doc/conf.py index 18aebb6..d4ee50d 100644 --- a/Doc/conf.py +++ b/Doc/conf.py @@ -89,13 +89,17 @@ html_split_index = True # ------------------------ # Get LaTeX to handle Unicode correctly -latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''} +latex_elements = { + 'inputenc': r'\usepackage[utf8x]{inputenc}', + 'utf8extra': '', + 'fontenc': r'\usepackage[T1,T2A]{fontenc}', +} # Additional stuff for the LaTeX preamble. latex_elements['preamble'] = r''' \authoraddress{ - \strong{Python Software Foundation}\\ - Email: \email{docs@python.org} + \sphinxstrong{Python Software Foundation}\\ + Email: \sphinxemail{docs@python.org} } \let\Verbatim=\OriginalVerbatim \let\endVerbatim=\endOriginalVerbatim @@ -105,7 +109,7 @@ latex_elements['preamble'] = r''' latex_elements['papersize'] = 'a4' # The font size ('10pt', '11pt' or '12pt'). -latex_elements['font_size'] = '10pt' +latex_elements['pointsize'] = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). diff --git a/Doc/copyright.rst b/Doc/copyright.rst index 22d7705..2b5400c 100644 --- a/Doc/copyright.rst +++ b/Doc/copyright.rst @@ -4,7 +4,7 @@ Copyright Python and this documentation is: -Copyright © 2001-2016 Python Software Foundation. All rights reserved. +Copyright © 2001-2017 Python Software Foundation. All rights reserved. Copyright © 2000 BeOpen.com. All rights reserved. diff --git a/Doc/extending/extending.rst b/Doc/extending/extending.rst index 4ac820a..9358462 100644 --- a/Doc/extending/extending.rst +++ b/Doc/extending/extending.rst @@ -333,12 +333,12 @@ function. The method table must be referenced in the module definition structure:: static struct PyModuleDef spammodule = { - PyModuleDef_HEAD_INIT, - "spam", /* name of module */ - spam_doc, /* module documentation, may be NULL */ - -1, /* size of per-interpreter state of the module, - or -1 if the module keeps state in global variables. */ - SpamMethods + PyModuleDef_HEAD_INIT, + "spam", /* name of module */ + spam_doc, /* module documentation, may be NULL */ + -1, /* size of per-interpreter state of the module, + or -1 if the module keeps state in global variables. */ + SpamMethods }; This structure, in turn, must be passed to the interpreter in the module's diff --git a/Doc/extending/newtypes.rst b/Doc/extending/newtypes.rst index 003b4e5..abd5da9 100644 --- a/Doc/extending/newtypes.rst +++ b/Doc/extending/newtypes.rst @@ -728,8 +728,9 @@ functions. With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be simplified: uniformity across these boring implementations. We also need to provide a method for clearing any subobjects that can -participate in cycles. We implement the method and reimplement the deallocator -to use it:: +participate in cycles. + +:: static int Noddy_clear(Noddy *self) @@ -747,13 +748,6 @@ to use it:: return 0; } - static void - Noddy_dealloc(Noddy* self) - { - Noddy_clear(self); - Py_TYPE(self)->tp_free((PyObject*)self); - } - Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the temporary variable so that we can set each member to *NULL* before decrementing its reference count. We do this because, as was discussed earlier, if the @@ -776,6 +770,23 @@ be simplified:: return 0; } +Note that :c:func:`Noddy_dealloc` may call arbitrary functions through +``__del__`` method or weakref callback. It means circular GC can be +triggered inside the function. Since GC assumes reference count is not zero, +we need to untrack the object from GC by calling :c:func:`PyObject_GC_UnTrack` +before clearing members. Here is reimplemented deallocator which uses +:c:func:`PyObject_GC_UnTrack` and :c:func:`Noddy_clear`. + +:: + + static void + Noddy_dealloc(Noddy* self) + { + PyObject_GC_UnTrack(self); + Noddy_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); + } + Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags:: Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ diff --git a/Doc/faq/general.rst b/Doc/faq/general.rst index 8f6a907..d4a97fd 100644 --- a/Doc/faq/general.rst +++ b/Doc/faq/general.rst @@ -167,7 +167,7 @@ several useful pieces of freely distributable software. The source will compile and run out of the box on most UNIX platforms. Consult the `Getting Started section of the Python Developer's Guide -`__ for more +`__ for more information on getting the source code and compiling it. @@ -223,7 +223,7 @@ newsgroups and on the Python home page at https://www.python.org/; an RSS feed o news is available. You can also access the development version of Python through Git. See -`The Python Developer's Guide `_ for details. +`The Python Developer's Guide `_ for details. How do I submit bug reports and patches for Python? @@ -239,7 +239,7 @@ report bugs to Python, you can obtain your Roundup password through Roundup's `password reset procedure `_. For more information on how Python is developed, consult `the Python Developer's -Guide `_. +Guide `_. Are there any published articles about Python that I can reference? diff --git a/Doc/faq/gui.rst b/Doc/faq/gui.rst index 477d8c6..38e1796 100644 --- a/Doc/faq/gui.rst +++ b/Doc/faq/gui.rst @@ -94,15 +94,6 @@ Python bindings for `the FLTK toolkit `_, a simple yet powerful and mature cross-platform windowing system, are available from `the PyFLTK project `_. - -FOX ----- - -A wrapper for `the FOX toolkit `_ called `FXpy -`_ is available. FOX supports both Unix variants -and Windows. - - OpenGL ------ diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index 9c5e20d..7476ce1 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -1638,7 +1638,7 @@ collected. Despite the cycle collector, it's still a good idea to define an explicit ``close()`` method on objects to be called whenever you're done with them. The -``close()`` method can then remove attributes that refer to subobjecs. Don't +``close()`` method can then remove attributes that refer to subobjects. Don't call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and ``close()`` should make sure that it can be called more than once for the same object. diff --git a/Doc/howto/curses.rst b/Doc/howto/curses.rst index 188a5cf..1d3bfb8 100644 --- a/Doc/howto/curses.rst +++ b/Doc/howto/curses.rst @@ -65,7 +65,7 @@ and full support for mouse and keyboard input. The Python curses module ------------------------ -Thy Python module is a fairly simple wrapper over the C functions provided by +The Python module is a fairly simple wrapper over the C functions provided by curses; if you're already familiar with curses programming in C, it's really easy to transfer that knowledge to Python. The biggest difference is that the Python interface makes things simpler by merging different C functions such as @@ -538,7 +538,7 @@ the Python interface. Often this isn't because they're difficult to implement, but because no one has needed them yet. Also, Python doesn't yet support the menu library associated with ncurses. Patches adding support for these would be welcome; see -`the Python Developer's Guide `_ to +`the Python Developer's Guide `_ to learn more about submitting patches to Python. * `Writing Programs with NCURSES `_: diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst index 2dd6c34..b349375 100644 --- a/Doc/howto/descriptor.rst +++ b/Doc/howto/descriptor.rst @@ -252,10 +252,10 @@ to wrap access to the value attribute in a property data descriptor:: class Cell(object): . . . - def getvalue(self, obj): - "Recalculate cell before returning value" + def getvalue(self): + "Recalculate the cell before returning value" self.recalc() - return obj._value + return self._value value = property(getvalue) diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst index 6498ea5..44f38e0 100644 --- a/Doc/howto/logging-cookbook.rst +++ b/Doc/howto/logging-cookbook.rst @@ -1258,8 +1258,8 @@ socket is created separately and passed to the handler (as its 'queue'):: class ZeroMQSocketHandler(QueueHandler): def enqueue(self, record): - data = json.dumps(record.__dict__) - self.queue.send(data) + self.queue.send_json(record.__dict__) + handler = ZeroMQSocketHandler(sock) @@ -1272,11 +1272,10 @@ data needed by the handler to create the socket:: self.ctx = ctx or zmq.Context() socket = zmq.Socket(self.ctx, socktype) socket.bind(uri) - QueueHandler.__init__(self, socket) + super().__init__(socket) def enqueue(self, record): - data = json.dumps(record.__dict__) - self.queue.send(data) + self.queue.send_json(record.__dict__) def close(self): self.queue.close() @@ -1292,12 +1291,13 @@ of queues, for example a ZeroMQ 'subscribe' socket. Here's an example:: def __init__(self, uri, *handlers, **kwargs): self.ctx = kwargs.get('ctx') or zmq.Context() socket = zmq.Socket(self.ctx, zmq.SUB) - socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything + socket.setsockopt_string(zmq.SUBSCRIBE, '') # subscribe to everything socket.connect(uri) + super().__init__(socket, *handlers, **kwargs) def dequeue(self): - msg = self.queue.recv() - return logging.makeLogRecord(json.loads(msg)) + msg = self.queue.recv_json() + return logging.makeLogRecord(msg) .. seealso:: diff --git a/Doc/includes/noddy4.c b/Doc/includes/noddy4.c index eb9622a..08ba4c3 100644 --- a/Doc/includes/noddy4.c +++ b/Doc/includes/noddy4.c @@ -46,6 +46,7 @@ Noddy_clear(Noddy *self) static void Noddy_dealloc(Noddy* self) { + PyObject_GC_UnTrack(self); Noddy_clear(self); Py_TYPE(self)->tp_free((PyObject*)self); } diff --git a/Doc/installing/index.rst b/Doc/installing/index.rst index b22465d..09bb825 100644 --- a/Doc/installing/index.rst +++ b/Doc/installing/index.rst @@ -211,6 +211,17 @@ On such systems, it is often better to use a virtual environment or a per-user installation when installing packages with ``pip``. +Pip not installed +----------------- + +It is possible that ``pip`` does not get installed by default. One potential fix is:: + + python -m ensurepip --default-pip + +There are also additional resources for `installing pip. +`__ + + Installing binary extensions ---------------------------- diff --git a/Doc/library/abc.rst b/Doc/library/abc.rst index 966003b..6001db3 100644 --- a/Doc/library/abc.rst +++ b/Doc/library/abc.rst @@ -24,7 +24,33 @@ a class or instance provides a particular interface, for example, is it hashable or a mapping. -This module provides the following classes: +This module provides the metaclass :class:`ABCMeta` for defining ABCs and +a helper class :class:`ABC` to alternatively define ABCs through inheritance: + +.. class:: ABC + + A helper class that has :class:`ABCMeta` as its metaclass. With this class, + an abstract base class can be created by simply deriving from :class:`ABC` + avoiding sometimes confusing metaclass usage, for example:: + + from abc import ABC + + class MyABC(ABC): + pass + + Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore + inheriting from :class:`ABC` requires the usual precautions regarding + metaclass usage, as multiple inheritance may lead to metaclass conflicts. + One may also define an abstract base class by passing the metaclass + keyword and using :class:`ABCMeta` directly, for example:: + + from abc import ABCMeta + + class MyABC(metaclass=ABCMeta): + pass + + .. versionadded:: 3.4 + .. class:: ABCMeta @@ -46,15 +72,15 @@ This module provides the following classes: Register *subclass* as a "virtual subclass" of this ABC. For example:: - from abc import ABCMeta + from abc import ABC - class MyABC(metaclass=ABCMeta): - pass + class MyABC(ABC): + pass - MyABC.register(tuple) + MyABC.register(tuple) - assert issubclass(tuple, MyABC) - assert isinstance((), MyABC) + assert issubclass(tuple, MyABC) + assert isinstance((), MyABC) .. versionchanged:: 3.3 Returns the registered subclass, to allow usage as a class decorator. @@ -95,7 +121,7 @@ This module provides the following classes: def get_iterator(self): return iter(self) - class MyIterable(metaclass=ABCMeta): + class MyIterable(ABC): @abstractmethod def __iter__(self): @@ -132,17 +158,6 @@ This module provides the following classes: available as a method of ``Foo``, so it is provided separately. -.. class:: ABC - - A helper class that has :class:`ABCMeta` as its metaclass. With this class, - an abstract base class can be created by simply deriving from :class:`ABC`, - avoiding sometimes confusing metaclass usage. - - Note that the type of :class:`ABC` is still :class:`ABCMeta`, therefore - inheriting from :class:`ABC` requires the usual precautions regarding metaclass - usage, as multiple inheritance may lead to metaclass conflicts. - - .. versionadded:: 3.4 The :mod:`abc` module also provides the following decorators: @@ -168,7 +183,7 @@ The :mod:`abc` module also provides the following decorators: descriptors, it should be applied as the innermost decorator, as shown in the following usage examples:: - class C(metaclass=ABCMeta): + class C(ABC): @abstractmethod def my_abstract_method(self, ...): ... @@ -230,7 +245,7 @@ The :mod:`abc` module also provides the following decorators: is now correctly identified as abstract when applied to an abstract method:: - class C(metaclass=ABCMeta): + class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, ...): @@ -251,7 +266,7 @@ The :mod:`abc` module also provides the following decorators: is now correctly identified as abstract when applied to an abstract method:: - class C(metaclass=ABCMeta): + class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(...): @@ -278,7 +293,7 @@ The :mod:`abc` module also provides the following decorators: is now correctly identified as abstract when applied to an abstract method:: - class C(metaclass=ABCMeta): + class C(ABC): @property @abstractmethod def my_abstract_property(self): @@ -288,7 +303,7 @@ The :mod:`abc` module also provides the following decorators: read-write abstract property by appropriately marking one or more of the underlying methods as abstract:: - class C(metaclass=ABCMeta): + class C(ABC): @property def x(self): ... diff --git a/Doc/library/aifc.rst b/Doc/library/aifc.rst index 23a9620..970a7ae 100644 --- a/Doc/library/aifc.rst +++ b/Doc/library/aifc.rst @@ -18,12 +18,6 @@ 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 ability to compress the audio data. -.. note:: - - Some operations may only work under IRIX; these will raise :exc:`ImportError` - when attempting to import the :mod:`cl` module, which is only available on - IRIX. - Audio files have a number of parameters that describe the audio data. The sampling rate or frame rate is the number of times per second the sound is sampled. The number of channels indicate if the audio is mono, stereo, or diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 4530304..27c7ba5 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -426,7 +426,9 @@ should not be line-wrapped:: -h, --help show this help message and exit :class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text, -including argument descriptions. +including argument descriptions. However, multiple new lines are replaced with +one. If you wish to preserve multiple blank lines, add spaces between the +newlines. :class:`ArgumentDefaultsHelpFormatter` automatically adds information about default values to each of the argument help messages:: @@ -898,6 +900,8 @@ values are: usage: PROG [-h] foo [foo ...] PROG: error: too few arguments +.. _`argparse.REMAINDER`: + * ``argparse.REMAINDER``. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities:: @@ -1324,8 +1328,11 @@ The parse_args() method created and how they are assigned. See the documentation for :meth:`add_argument` for details. - By default, the argument strings are taken from :data:`sys.argv`, and a new empty - :class:`Namespace` object is created for the attributes. + * args_ - List of strings to parse. The default is taken from + :data:`sys.argv`. + + * namespace_ - An object to take the attributes. The default is a new empty + :class:`Namespace` object. Option value syntax @@ -1467,6 +1474,7 @@ unambiguous (the prefix matches a unique option):: An error is produced for arguments that could produce more than one options. This feature can be disabled by setting :ref:`allow_abbrev` to ``False``. +.. _args: Beyond ``sys.argv`` ^^^^^^^^^^^^^^^^^^^ @@ -1488,6 +1496,7 @@ interactive prompt:: >>> parser.parse_args(['1', '2', '3', '4', '--sum']) Namespace(accumulate=, integers=[1, 2, 3, 4]) +.. _namespace: The Namespace object ^^^^^^^^^^^^^^^^^^^^ @@ -2008,7 +2017,12 @@ A partial upgrade path from :mod:`optparse` to :mod:`argparse`: * Replace ``(options, args) = parser.parse_args()`` with ``args = parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the positional arguments. Keep in mind that what was previously - called ``options``, now in :mod:`argparse` context is called ``args``. + called ``options``, now in the :mod:`argparse` context is called ``args``. + +* Replace :meth:`optparse.OptionParser.disable_interspersed_args` + by setting ``nargs`` of a positional argument to `argparse.REMAINDER`_, or + use :meth:`~ArgumentParser.parse_known_args` to collect unparsed argument + strings in a separate list. * Replace callback actions and the ``callback_*`` keyword arguments with ``type`` or ``action`` arguments. diff --git a/Doc/library/asyncio-dev.rst b/Doc/library/asyncio-dev.rst index cc4a14b..1838eb9 100644 --- a/Doc/library/asyncio-dev.rst +++ b/Doc/library/asyncio-dev.rst @@ -52,7 +52,7 @@ Cancellation ------------ Cancellation of tasks is not common in classic programming. In asynchronous -programming, not only it is something common, but you have to prepare your +programming, not only is it something common, but you have to prepare your code to handle it. Futures and tasks can be cancelled explicitly with their :meth:`Future.cancel` diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst index fa6a296..83bbb70 100644 --- a/Doc/library/asyncio-eventloop.rst +++ b/Doc/library/asyncio-eventloop.rst @@ -5,6 +5,8 @@ Base Event Loop =============== +**Source code:** :source:`Lib/asyncio/events.py` + The event loop is the central execution device provided by :mod:`asyncio`. It provides multiple facilities, including: diff --git a/Doc/library/asyncio-eventloops.rst b/Doc/library/asyncio-eventloops.rst index 1dc18fc..d74fcb1 100644 --- a/Doc/library/asyncio-eventloops.rst +++ b/Doc/library/asyncio-eventloops.rst @@ -3,6 +3,8 @@ Event loops =========== +**Source code:** :source:`Lib/asyncio/events.py` + Event loop functions -------------------- diff --git a/Doc/library/asyncio-protocol.rst b/Doc/library/asyncio-protocol.rst index 3f55506..cd84ae7 100644 --- a/Doc/library/asyncio-protocol.rst +++ b/Doc/library/asyncio-protocol.rst @@ -1,8 +1,12 @@ .. currentmodule:: asyncio -++++++++++++++++++++++++++++++++++++++++++++++ -Transports and protocols (callback based API) -++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++ +Transports and protocols (callback based API) ++++++++++++++++++++++++++++++++++++++++++++++ + +**Source code:** :source:`Lib/asyncio/transports.py` + +**Source code:** :source:`Lib/asyncio/protocols.py` .. _asyncio-transport: @@ -163,11 +167,17 @@ WriteTransport Set the *high*- and *low*-water limits for write flow control. - These two values control when call the protocol's + These two values (measured in number of + bytes) control when the protocol's :meth:`pause_writing` and :meth:`resume_writing` methods are called. If specified, the low-water limit must be less than or equal to the high-water limit. Neither *high* nor *low* can be negative. + :meth:`pause_writing` is called when the buffer size becomes greater + than or equal to the *high* value. If writing has been paused, + :meth:`resume_writing` is called when the buffer size becomes less + than or equal to the *low* value. + The defaults are implementation-specific. If only the high-water limit is given, the low-water limit defaults to an implementation-specific value less than or equal to the diff --git a/Doc/library/asyncio-queue.rst b/Doc/library/asyncio-queue.rst index f11c09a..ea78755 100644 --- a/Doc/library/asyncio-queue.rst +++ b/Doc/library/asyncio-queue.rst @@ -3,6 +3,8 @@ Queues ====== +**Source code:** :source:`Lib/asyncio/queues.py` + Queues: * :class:`Queue` diff --git a/Doc/library/asyncio-stream.rst b/Doc/library/asyncio-stream.rst index 6177b4b..491afdd 100644 --- a/Doc/library/asyncio-stream.rst +++ b/Doc/library/asyncio-stream.rst @@ -6,6 +6,8 @@ Streams (coroutine based API) +++++++++++++++++++++++++++++ +**Source code:** :source:`Lib/asyncio/streams.py` + Stream functions ================ diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst index 16ba9a3..1c1d0be 100644 --- a/Doc/library/asyncio-subprocess.rst +++ b/Doc/library/asyncio-subprocess.rst @@ -5,6 +5,8 @@ Subprocess ========== +**Source code:** :source:`Lib/asyncio/subprocess.py` + Windows event loop ------------------ diff --git a/Doc/library/asyncio-sync.rst b/Doc/library/asyncio-sync.rst index 0909352..14e3def 100644 --- a/Doc/library/asyncio-sync.rst +++ b/Doc/library/asyncio-sync.rst @@ -4,6 +4,8 @@ Synchronization primitives ========================== +**Source code:** :source:`Lib/asyncio/locks.py` + Locks: * :class:`Lock` diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index 804f192..5298c11 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -3,6 +3,10 @@ Tasks and coroutines ==================== +**Source code:** :source:`Lib/asyncio/tasks.py` + +**Source code:** :source:`Lib/asyncio/coroutines.py` + .. _coroutine: Coroutines diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst index 0ecd89b..b9c1868 100644 --- a/Doc/library/codecs.rst +++ b/Doc/library/codecs.rst @@ -554,19 +554,19 @@ define in order to be compatible with the Python codec registry. if necessary, to reset the encoder and to get the output. -.. method:: IncrementalEncoder.getstate() + .. method:: getstate() - Return the current state of the encoder which must be an integer. The - implementation should make sure that ``0`` is the most common state. (States - that are more complicated than integers can be converted into an integer by - marshaling/pickling the state and encoding the bytes of the resulting string - into an integer). + Return the current state of the encoder which must be an integer. The + implementation should make sure that ``0`` is the most common + state. (States that are more complicated than integers can be converted + into an integer by marshaling/pickling the state and encoding the bytes + of the resulting string into an integer). -.. method:: IncrementalEncoder.setstate(state) + .. method:: setstate(state) - Set the state of the encoder to *state*. *state* must be an encoder state - returned by :meth:`getstate`. + Set the state of the encoder to *state*. *state* must be an encoder state + returned by :meth:`getstate`. .. _incremental-decoder-objects: diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 6621f4a..bd4c94f 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -81,9 +81,24 @@ are always available. They are listed here in alphabetical order. .. function:: bin(x) - Convert an integer number to a binary string. The result is a valid Python - expression. If *x* is not a Python :class:`int` object, it has to define an - :meth:`__index__` method that returns an integer. + Convert an integer number to a binary string prefixed with "0b". The result + is a valid Python expression. If *x* is not a Python :class:`int` object, it + has to define an :meth:`__index__` method that returns an integer. Some + examples: + + >>> bin(3) + '0b11' + >>> bin(-10) + '-0b1010' + + If prefix "0b" is desired or not, you can use either of the following ways. + + >>> format(14, '#b'), format(14, 'b') + ('0b1110', '1110') + >>> f'{14:#b}', f'{14:b}' + ('0b1110', '1110') + + See also :func:`format` for more information. .. class:: bool([x]) @@ -635,16 +650,26 @@ are always available. They are listed here in alphabetical order. .. function:: hex(x) - Convert an integer number to a lowercase hexadecimal string - prefixed with "0x", for example: + Convert an integer number to a lowercase hexadecimal string prefixed with + "0x". If x is not a Python :class:`int` object, it has to define an + __index__() method that returns an integer. Some examples: >>> hex(255) '0xff' >>> hex(-42) '-0x2a' - If x is not a Python :class:`int` object, it has to define an __index__() - method that returns an integer. + If you want to convert an integer number to an uppercase or lower hexadecimal + string with prefix or not, you can use either of the following ways: + + >>> '%#x' % 255, '%x' % 255, '%X' % 255 + ('0xff', 'ff', 'FF') + >>> format(255, '#x'), format(255, 'x'), format(255, 'X') + ('0xff', 'ff', 'FF') + >>> f'{255:#x}', f'{255:x}', f'{255:X}' + ('0xff', 'ff', 'FF') + + See also :func:`format` for more information. See also :func:`int` for converting a hexadecimal string to an integer using a base of 16. @@ -878,10 +903,27 @@ are always available. They are listed here in alphabetical order. .. function:: oct(x) - Convert an integer number to an octal string. The result is a valid Python - expression. If *x* is not a Python :class:`int` object, it has to define an - :meth:`__index__` method that returns an integer. + Convert an integer number to an octal string prefixed with "0o". The result + is a valid Python expression. If *x* is not a Python :class:`int` object, it + has to define an :meth:`__index__` method that returns an integer. For + example: + + >>> oct(8) + '0o10' + >>> oct(-56) + '-0o70' + + If you want to convert an integer number to octal string either with prefix + "0o" or not, you can use either of the following ways. + + >>> '%#o' % 10, '%o' % 10 + ('0o12', '12') + >>> format(10, '#o'), format(10, 'o') + ('0o12', '12') + >>> f'{10:#o}', f'{10:o}' + ('0o12', '12') + See also :func:`format` for more information. .. index:: single: file object; open() built-in function @@ -1319,7 +1361,7 @@ are always available. They are listed here in alphabetical order. :func:`itertools.islice` for an alternate version that returns an iterator. -.. function:: sorted(iterable[, key][, reverse]) +.. function:: sorted(iterable, *, key=None, reverse=False) Return a new sorted list from the items in *iterable*. diff --git a/Doc/library/gettext.rst b/Doc/library/gettext.rst index 3a87bf5..053d9d3 100644 --- a/Doc/library/gettext.rst +++ b/Doc/library/gettext.rst @@ -48,9 +48,10 @@ class-based API instead. .. function:: bind_textdomain_codeset(domain, codeset=None) - Bind the *domain* to *codeset*, changing the encoding of strings returned by the - :func:`gettext` family of functions. If *codeset* is omitted, then the current - binding is returned. + Bind the *domain* to *codeset*, changing the encoding of byte strings + returned by the :func:`lgettext`, :func:`ldgettext`, :func:`lngettext` + and :func:`ldngettext` functions. + If *codeset* is omitted, then the current binding is returned. .. function:: textdomain(domain=None) @@ -67,28 +68,14 @@ class-based API instead. :func:`_` in the local namespace (see examples below). -.. function:: lgettext(message) - - Equivalent to :func:`gettext`, but the translation is returned in the - preferred system encoding, if no other encoding was explicitly set with - :func:`bind_textdomain_codeset`. - - .. function:: dgettext(domain, message) - Like :func:`gettext`, but look the message up in the specified *domain*. - - -.. function:: ldgettext(domain, message) - - Equivalent to :func:`dgettext`, but the translation is returned in the - preferred system encoding, if no other encoding was explicitly set with - :func:`bind_textdomain_codeset`. + Like :func:`.gettext`, but look the message up in the specified *domain*. .. function:: ngettext(singular, plural, n) - Like :func:`gettext`, but consider plural forms. If a translation is found, + Like :func:`.gettext`, but consider plural forms. If a translation is found, apply the plural formula to *n*, and return the resulting message (some languages have more than two plural forms). If no translation is found, return *singular* if *n* is 1; return *plural* otherwise. @@ -101,24 +88,33 @@ class-based API instead. formulas for a variety of languages. -.. function:: lngettext(singular, plural, n) - - Equivalent to :func:`ngettext`, but the translation is returned in the - preferred system encoding, if no other encoding was explicitly set with - :func:`bind_textdomain_codeset`. - - .. function:: dngettext(domain, singular, plural, n) Like :func:`ngettext`, but look the message up in the specified *domain*. +.. function:: lgettext(message) +.. function:: ldgettext(domain, message) +.. function:: lngettext(singular, plural, n) .. function:: ldngettext(domain, singular, plural, n) - Equivalent to :func:`dngettext`, but the translation is returned in the - preferred system encoding, if no other encoding was explicitly set with + Equivalent to the corresponding functions without the ``l`` prefix + (:func:`.gettext`, :func:`dgettext`, :func:`ngettext` and :func:`dngettext`), + but the translation is returned as a byte string encoded in the preferred + system encoding if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. + .. warning:: + + These functions should be avoided in Python 3, because they return + encoded bytes. It's much better to use alternatives which return + Unicode strings instead, since most Python applications will want to + manipulate human readable text as strings instead of bytes. Further, + it's possible that you may get unexpected Unicode-related exceptions + if there are encoding problems with the translated strings. It is + possible that the ``l*()`` functions will be deprecated in future Python + versions due to their inherent problems and limitations. + Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but this was deemed not useful and so it is currently unimplemented. @@ -179,8 +175,9 @@ class can also install themselves in the built-in namespace as the function names are cached. The actual class instantiated is either *class_* if provided, otherwise :class:`GNUTranslations`. The class's constructor must take a single :term:`file object` argument. If provided, *codeset* will change - the charset used to encode translated strings in the :meth:`lgettext` and - :meth:`lngettext` methods. + the charset used to encode translated strings in the + :meth:`~NullTranslations.lgettext` and :meth:`~NullTranslations.lngettext` + methods. If multiple files are found, later files are used as fallbacks for earlier ones. To allow setting the fallback, :func:`copy.copy` is used to clone each @@ -250,26 +247,29 @@ are the methods of :class:`NullTranslations`: .. method:: gettext(message) - If a fallback has been set, forward :meth:`gettext` to the fallback. - Otherwise, return the translated message. Overridden in derived classes. - - - .. method:: lgettext(message) - - If a fallback has been set, forward :meth:`lgettext` to the fallback. - Otherwise, return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`.gettext` to the fallback. + Otherwise, return *message*. Overridden in derived classes. .. method:: ngettext(singular, plural, n) If a fallback has been set, forward :meth:`ngettext` to the fallback. - Otherwise, return the translated message. Overridden in derived classes. + Otherwise, return *singular* if *n* is 1; return *plural* otherwise. + Overridden in derived classes. + .. method:: lgettext(message) .. method:: lngettext(singular, plural, n) - If a fallback has been set, forward :meth:`lngettext` to the fallback. - Otherwise, return the translated message. Overridden in derived classes. + Equivalent to :meth:`.gettext` and :meth:`ngettext`, but the translation + is returned as a byte string encoded in the preferred system encoding + if no encoding was explicitly set with :meth:`set_output_charset`. + Overridden in derived classes. + + .. warning:: + + These methods should be avoided in Python 3. See the warning for the + :func:`lgettext` function. .. method:: info() @@ -279,32 +279,28 @@ are the methods of :class:`NullTranslations`: .. method:: charset() - Return the "protected" :attr:`_charset` variable, which is the encoding of - the message catalog file. + Return the encoding of the message catalog file. .. method:: output_charset() - Return the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages in :meth:`lgettext` and - :meth:`lngettext`. + Return the encoding used to return translated messages in :meth:`.lgettext` + and :meth:`.lngettext`. .. method:: set_output_charset(charset) - Change the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + Change the encoding used to return translated messages. .. method:: install(names=None) - This method installs :meth:`self.gettext` into the built-in namespace, + This method installs :meth:`.gettext` into the built-in namespace, binding it to ``_``. If the *names* parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in - addition to :func:`_`. Supported names are ``'gettext'`` (bound to - :meth:`self.gettext`), ``'ngettext'`` (bound to :meth:`self.ngettext`), + addition to :func:`_`. Supported names are ``'gettext'``, ``'ngettext'``, ``'lgettext'`` and ``'lngettext'``. Note that this is only one way, albeit the most convenient way, to make @@ -349,49 +345,52 @@ If the :file:`.mo` file's magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a :class:`GNUTranslations` class can raise :exc:`OSError`. -The following methods are overridden from the base class implementation: - +.. class:: GNUTranslations -.. method:: GNUTranslations.gettext(message) + The following methods are overridden from the base class implementation: - Look up the *message* id in the catalog and return the corresponding message - string, as a Unicode string. If there is no entry in the catalog for the - *message* id, and a fallback has been set, the look up is forwarded to the - fallback's :meth:`gettext` method. Otherwise, the *message* id is returned. + .. method:: gettext(message) + Look up the *message* id in the catalog and return the corresponding message + string, as a Unicode string. If there is no entry in the catalog for the + *message* id, and a fallback has been set, the look up is forwarded to the + fallback's :meth:`~NullTranslations.gettext` method. Otherwise, the + *message* id is returned. -.. method:: GNUTranslations.lgettext(message) - Equivalent to :meth:`gettext`, but the translation is returned as a - bytestring encoded in the selected output charset, or in the preferred system - encoding if no encoding was explicitly set with :meth:`set_output_charset`. + .. method:: ngettext(singular, plural, n) + Do a plural-forms lookup of a message id. *singular* is used as the message id + for purposes of lookup in the catalog, while *n* is used to determine which + plural form to use. The returned message string is a Unicode string. -.. method:: GNUTranslations.ngettext(singular, plural, n) + If the message id is not found in the catalog, and a fallback is specified, + the request is forwarded to the fallback's :meth:`~NullTranslations.ngettext` + method. Otherwise, when *n* is 1 *singular* is returned, and *plural* is + returned in all other cases. - Do a plural-forms lookup of a message id. *singular* is used as the message id - for purposes of lookup in the catalog, while *n* is used to determine which - plural form to use. The returned message string is a Unicode string. + Here is an example:: - If the message id is not found in the catalog, and a fallback is specified, the - request is forwarded to the fallback's :meth:`ngettext` method. Otherwise, when - *n* is 1 *singular* is returned, and *plural* is returned in all other cases. + n = len(os.listdir('.')) + cat = GNUTranslations(somefile) + message = cat.ngettext( + 'There is %(num)d file in this directory', + 'There are %(num)d files in this directory', + n) % {'num': n} - Here is an example:: - n = len(os.listdir('.')) - cat = GNUTranslations(somefile) - message = cat.ngettext( - 'There is %(num)d file in this directory', - 'There are %(num)d files in this directory', - n) % {'num': n} + .. method:: lgettext(message) + .. method:: lngettext(singular, plural, n) + Equivalent to :meth:`.gettext` and :meth:`.ngettext`, but the translation + is returned as a byte string encoded in the preferred system encoding + if no encoding was explicitly set with + :meth:`~NullTranslations.set_output_charset`. -.. method:: GNUTranslations.lngettext(singular, plural, n) + .. warning:: - Equivalent to :meth:`gettext`, but the translation is returned as a - bytestring encoded in the selected output charset, or in the preferred system - encoding if no encoding was explicitly set with :meth:`set_output_charset`. + These methods should be avoided in Python 3. See the warning for the + :func:`lgettext` function. Solaris message catalog support @@ -509,7 +508,7 @@ module:: import gettext t = gettext.translation('spam', '/usr/share/locale') - _ = t.lgettext + _ = t.gettext Localizing your application diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst index 9d56356..725dce6 100644 --- a/Doc/library/hashlib.rst +++ b/Doc/library/hashlib.rst @@ -506,8 +506,9 @@ to users and later verify them to make sure they weren't tampered with:: >>> AUTH_SIZE = 16 >>> >>> def sign(cookie): - ... h = blake2b(data=cookie, digest_size=AUTH_SIZE, key=SECRET_KEY) - ... return h.hexdigest() + ... h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY) + ... h.update(cookie) + ... return h.hexdigest().encode('utf-8') >>> >>> cookie = b'user:vatrogasac' >>> sig = sign(cookie) @@ -517,7 +518,7 @@ to users and later verify them to make sure they weren't tampered with:: True >>> compare_digest(b'user:policajac', sig) False - >>> compare_digesty(cookie, '0102030405060708090a0b0c0d0e0f00') + >>> compare_digest(cookie, b'0102030405060708090a0b0c0d0e0f00') False Even though there's a native keyed hashing mode, BLAKE2 can, of course, be used diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst index a945b6d..af15359 100644 --- a/Doc/library/idle.rst +++ b/Doc/library/idle.rst @@ -190,7 +190,9 @@ Format Paragraph paragraph will be formatted to less than N columns, where N defaults to 72. Strip trailing whitespace - Remove any space characters after the last non-space character of a line. + Remove trailing space and other whitespace characters after the last + non-whitespace character of a line by applying str.rstrip to each line, + including lines within multiline strings. .. index:: single: Run script @@ -599,15 +601,15 @@ starting from a console (``python -m idlelib)`` and see if a message appears. IDLE-console differences ^^^^^^^^^^^^^^^^^^^^^^^^ -As much as possible, the result of executing Python code with IDLE is the -same as executing the same code in a console window. However, the different -interface and operation occasionally affect visible results. For instance, -``sys.modules`` starts with more entries. +With rare exceptions, the result of executing Python code with IDLE is +intended to be the same as executing the same code in a console window. +However, the different interface and operation occasionally affect +visible results. For instance, ``sys.modules`` starts with more entries. IDLE also replaces ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` with objects that get input from and send output to the Shell window. -When this window has the focus, it controls the keyboard and screen. -This is normally transparent, but functions that directly access the keyboard +When Shell has the focus, it controls the keyboard and screen. This is +normally transparent, but functions that directly access the keyboard and screen will not work. If ``sys`` is reset with ``importlib.reload(sys)``, IDLE's changes are lost and things like ``input``, ``raw_input``, and ``print`` will not work correctly. @@ -617,6 +619,29 @@ Some consoles only work with a single physical line at a time. IDLE uses ``exec`` to run each statement. As a result, ``'__builtins__'`` is always defined for each statement. +Developing tkinter applications +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +IDLE is intentionally different from standard Python in order to +facilitate development of tkinter programs. Enter ``import tkinter as tk; +root = tk.Tk()`` in standard Python and nothing appears. Enter the same +in IDLE and a tk window appears. In standard Python, one must also enter +``root.update()`` to see the window. IDLE does the equivalent in the +background, about 20 times a second, which is about every 50 milleseconds. +Next enter ``b = tk.Button(root, text='button'); b.pack()``. Again, +nothing visibly changes in standard Python until one enters ``root.update()``. + +Most tkinter programs run ``root.mainloop()``, which usually does not +return until the tk app is destroyed. If the program is run with +``python -i`` or from an IDLE editor, a ``>>>`` shell prompt does not +appear until ``mainloop()`` returns, at which time there is nothing left +to interact with. + +When running a tkinter program from an IDLE editor, one can comment out +the mainloop call. One then gets a shell prompt immediately and can +interact with the live application. One just has to remember to +re-enable the mainloop call when running in standard Python. + Running without a subprocess ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -671,24 +696,7 @@ Extensions ^^^^^^^^^^ IDLE contains an extension facility. Preferences for extensions can be -changed with Configure Extensions. See the beginning of config-extensions.def -in the idlelib directory for further information. The default extensions -are currently: - -* FormatParagraph - -* AutoExpand - -* ZoomHeight - -* ScriptBinding - -* CallTips - -* ParenMatch - -* AutoComplete - -* CodeContext - -* RstripExtension +changed with the Extensions tab of the preferences dialog. See the +beginning of config-extensions.def in the idlelib directory for further +information. The only current default extension is zzdummy, an example +also used for testing. diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst index 1fd5698..6406e30 100644 --- a/Doc/library/importlib.rst +++ b/Doc/library/importlib.rst @@ -32,7 +32,7 @@ generically as an :term:`importer`) to participate in the import process. :ref:`import` The language reference for the :keyword:`import` statement. - `Packages specification `__ + `Packages specification `__ Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on ``None`` in :data:`sys.modules`). diff --git a/Doc/library/json.rst b/Doc/library/json.rst index fdbdcb1..829218d 100644 --- a/Doc/library/json.rst +++ b/Doc/library/json.rst @@ -43,7 +43,7 @@ Encoding basic Python object hierarchies:: Compact encoding:: >>> import json - >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':')) + >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 96d1424..2f770b6 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -1024,7 +1024,7 @@ Connection objects are usually created using :func:`Pipe` -- see also .. method:: recv() Return an object sent from the other end of the connection using - :meth:`send`. Blocks until there its something to receive. Raises + :meth:`send`. Blocks until there is something to receive. Raises :exc:`EOFError` if there is nothing left to receive and the other end was closed. diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 5ae304d..56fc4ed 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -490,9 +490,10 @@ form. .. function:: compile(pattern, flags=0) - Compile a regular expression pattern into a regular expression object, which - can be used for matching using its :func:`~regex.match` and - :func:`~regex.search` methods, described below. + Compile a regular expression pattern into a :ref:`regular expression object + `, which can be used for matching using its + :func:`~regex.match`, :func:`~regex.search` and other methods, described + below. The expression's behaviour can be modified by specifying a *flags* value. Values can be any of the following variables, combined using bitwise OR (the @@ -541,9 +542,11 @@ form. .. data:: I IGNORECASE - Perform case-insensitive matching; expressions like ``[A-Z]`` will match - lowercase letters, too. This is not affected by the current locale - and works for Unicode characters as expected. + Perform case-insensitive matching; expressions like ``[A-Z]`` will also + match lowercase letters. The current locale does not change the effect of + this flag. Full Unicode matching (such as ``Ü`` matching ``ü``) also + works unless the :const:`re.ASCII` flag is also used to disable non-ASCII + matches. .. data:: L diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst index 6c30a74..d7e0467 100644 --- a/Doc/library/ssl.rst +++ b/Doc/library/ssl.rst @@ -193,11 +193,11 @@ instead. .. table:: ======================== ============ ============ ============= ========= =========== =========== - *client* / **server** **SSLv2** **SSLv3** **TLS** **TLSv1** **TLSv1.1** **TLSv1.2** + *client* / **server** **SSLv2** **SSLv3** **TLS** [3]_ **TLSv1** **TLSv1.1** **TLSv1.2** ------------------------ ------------ ------------ ------------- --------- ----------- ----------- *SSLv2* yes no no [1]_ no no no *SSLv3* no yes no [2]_ no no no - *TLS* (*SSLv23*) no [1]_ no [2]_ yes yes yes yes + *TLS* (*SSLv23*) [3]_ no [1]_ no [2]_ yes yes yes yes *TLSv1* no no yes yes no no *TLSv1.1* no no yes no yes no *TLSv1.2* no no yes no no yes @@ -206,6 +206,9 @@ instead. .. rubric:: Footnotes .. [1] :class:`SSLContext` disables SSLv2 with :data:`OP_NO_SSLv2` by default. .. [2] :class:`SSLContext` disables SSLv3 with :data:`OP_NO_SSLv3` by default. + .. [3] TLS 1.3 protocol will be available with :data:`PROTOCOL_TLS` in + OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just + TLS 1.3. .. note:: @@ -294,6 +297,11 @@ purposes. 3DES was dropped from the default cipher string. + .. versionchanged:: 3.6.3 + + TLS 1.3 cipher suites TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, + and TLS_CHACHA20_POLY1305_SHA256 were added to the default cipher string. + Random generation ^^^^^^^^^^^^^^^^^ @@ -760,6 +768,16 @@ Constants .. versionadded:: 3.4 +.. data:: OP_NO_TLSv1_3 + + Prevents a TLSv1.3 connection. This option is only applicable in conjunction + with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as + the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. + When Python has been compiled against an older version of OpenSSL, the + flag defaults to *0*. + + .. versionadded:: 3.6.3 + .. data:: OP_CIPHER_SERVER_PREFERENCE Use the server's cipher ordering preference, rather than the client's. @@ -834,6 +852,12 @@ Constants .. versionadded:: 3.3 +.. data:: HAS_TLSv1_3 + + Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. + + .. versionadded:: 3.6.3 + .. data:: CHANNEL_BINDING_TYPES List of supported TLS channel binding types. Strings in this list @@ -1442,8 +1466,9 @@ to speed up repeated connections from the same clients. This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is False. - OpenSSL 1.1.0+ will abort the handshake and raise :exc:`SSLError` when - both sides support ALPN but cannot agree on a protocol. + OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise :exc:`SSLError` + when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ + behaves like 1.0.2, :meth:`SSLSocket.selected_alpn_protocol` returns None. .. versionadded:: 3.5 @@ -2320,3 +2345,9 @@ successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or `IANA TLS: Transport Layer Security (TLS) Parameters `_ IANA + + `RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) `_ + IETF + + `Mozilla's Server Side TLS recommendations `_ + Mozilla diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 083fe53..b8c4d59 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -39,31 +39,26 @@ Truth Value Testing single: false Any object can be tested for truth value, for use in an :keyword:`if` or -:keyword:`while` condition or as operand of the Boolean operations below. The -following values are considered false: +:keyword:`while` condition or as operand of the Boolean operations below. - .. index:: single: None (Built-in object) - -* ``None`` - - .. index:: single: False (Built-in object) - -* ``False`` - -* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``. +.. index:: single: true -* any empty sequence, for example, ``''``, ``()``, ``[]``. +By default, an object is considered true unless its class defines either a +:meth:`__bool__` method that returns ``False`` or a :meth:`__len__` method that +returns zero, when called with the object. [1]_ Here are most of the built-in +objects considered false: -* any empty mapping, for example, ``{}``. + .. index:: + single: None (Built-in object) + single: False (Built-in object) -* instances of user-defined classes, if the class defines a :meth:`__bool__` or - :meth:`__len__` method, when that method returns the integer zero or - :class:`bool` value ``False``. [1]_ +* constants defined to be false: ``None`` and ``False``. -.. index:: single: true +* zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, + ``Fraction(0, 1)`` -All other values are considered true --- so objects of many types are always -true. +* empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, + ``range(0)`` .. index:: operator: or @@ -354,7 +349,7 @@ Notes: The numeric literals accepted include the digits ``0`` to ``9`` or any Unicode equivalent (code points with the ``Nd`` property). - See http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedNumericType.txt + See http://www.unicode.org/Public/9.0.0/ucd/extracted/DerivedNumericType.txt for a complete list of code points with the ``Nd`` property. @@ -1161,7 +1156,7 @@ application). :ref:`mutable ` sequence operations. Lists also provide the following additional method: - .. method:: list.sort(*, key=None, reverse=None) + .. method:: list.sort(*, key=None, reverse=False) This method sorts the list in place, using only ``<`` comparisons between items. Exceptions are not suppressed - if any comparison operations diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst index 548e4a6..27f3e82 100644 --- a/Doc/library/subprocess.rst +++ b/Doc/library/subprocess.rst @@ -38,7 +38,7 @@ compatibility with older versions, see the :ref:`call-function-trio` section. .. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\ - shell=False, timeout=None, check=False, \ + shell=False, cwd=None, timeout=None, check=False, \ encoding=None, errors=None) Run the command described by *args*. Wait for command to complete, then @@ -856,7 +856,7 @@ Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use :func:`run` in many cases, but lots of existing code calls these functions. -.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) +.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None) Run the command described by *args*. Wait for command to complete, then return the :attr:`~Popen.returncode` attribute. @@ -882,7 +882,7 @@ calls these functions. .. versionchanged:: 3.3 *timeout* was added. -.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) +.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None) Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise :exc:`CalledProcessError`. The @@ -912,7 +912,7 @@ calls these functions. .. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \ - encoding=None, errors=None, \ + cwd=None, encoding=None, errors=None, \ universal_newlines=False, timeout=None) Run command with arguments and return its output. @@ -1166,27 +1166,32 @@ handling consistency are valid for these functions. .. function:: getstatusoutput(cmd) - Return ``(status, output)`` of executing *cmd* in a shell. + Return ``(exitcode, output)`` of executing *cmd* in a shell. Execute the string *cmd* in a shell with :meth:`Popen.check_output` and - return a 2-tuple ``(status, output)``. The locale encoding is used; + return a 2-tuple ``(exitcode, output)``. The locale encoding is used; see the notes on :ref:`frequently-used-arguments` for more details. A trailing newline is stripped from the output. - The exit status for the command can be interpreted - according to the rules for the C function :c:func:`wait`. Example:: + The exit code for the command can be interpreted as the return code + of subprocess. Example:: >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') >>> subprocess.getstatusoutput('cat /bin/junk') - (256, 'cat: /bin/junk: No such file or directory') + (1, 'cat: /bin/junk: No such file or directory') >>> subprocess.getstatusoutput('/bin/junk') - (256, 'sh: /bin/junk: not found') + (127, 'sh: /bin/junk: not found') + >>> subprocess.getstatusoutput('/bin/kill $$') + (-15, '') Availability: POSIX & Windows .. versionchanged:: 3.3.4 - Windows support added + Windows support was added. + + The function now returns (exitcode, output) instead of (status, output) + as it did in Python 3.3.3 and earlier. See :func:`WEXITSTATUS`. .. function:: getoutput(cmd) diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst index cda859f..021e29e 100644 --- a/Doc/library/threading.rst +++ b/Doc/library/threading.rst @@ -875,8 +875,8 @@ Barrier Objects This class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other. Each of the threads tries to pass the barrier by calling the :meth:`~Barrier.wait` method and will block until -all of the threads have made the call. At this points, the threads are released -simultaneously. +all of the threads have made their :meth:`~Barrier.wait` calls. At this point, +the threads are released simultaneously. The barrier can be reused any number of times for the same number of threads. diff --git a/Doc/library/tokenize.rst b/Doc/library/tokenize.rst index ff55aac..afed36b 100644 --- a/Doc/library/tokenize.rst +++ b/Doc/library/tokenize.rst @@ -16,8 +16,9 @@ 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. -To simplify token stream handling, all :ref:`operators` and :ref:`delimiters` -tokens are returned using the generic :data:`token.OP` token type. The exact +To simplify token stream handling, all :ref:`operator ` and +:ref:`delimiter ` tokens and :data:`Ellipsis` are returned using +the generic :data:`~token.OP` token type. The exact type can be determined by checking the ``exact_type`` property on the :term:`named tuple` returned from :func:`tokenize.tokenize`. diff --git a/Doc/library/turtle.rst b/Doc/library/turtle.rst index 31761be..2b5d3e5 100644 --- a/Doc/library/turtle.rst +++ b/Doc/library/turtle.rst @@ -2368,7 +2368,7 @@ The demo scripts are: | wikipedia | a pattern from the wikipedia | :func:`clone`, | | | article on turtle graphics | :func:`undo` | +----------------+------------------------------+-----------------------+ -| yingyang | another elementary example | :func:`circle` | +| yinyang | another elementary example | :func:`circle` | +----------------+------------------------------+-----------------------+ Have fun! diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 1780739..1e48fec 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -939,7 +939,7 @@ The module defines the following classes, functions and decorators: Union[int, str] == Union[str, int] - * When a class and its subclass are present, the former is skipped, e.g.:: + * When a class and its subclass are present, the latter is skipped, e.g.:: Union[int, object] == object diff --git a/Doc/make.bat b/Doc/make.bat index b1a3738..968b20b 100644 --- a/Doc/make.bat +++ b/Doc/make.bat @@ -5,8 +5,30 @@ pushd %~dp0 set this=%~n0 -if "%SPHINXBUILD%" EQU "" set SPHINXBUILD=sphinx-build -if "%PYTHON%" EQU "" set PYTHON=py +call ..\PCBuild\find_python.bat %PYTHON% +if not defined SPHINXBUILD if defined PYTHON ( + %PYTHON% -c "import sphinx" > nul 2> nul + if errorlevel 1 ( + echo Installing sphinx with %PYTHON% + %PYTHON% -m pip install sphinx + if errorlevel 1 exit /B + ) + set SPHINXBUILD=%PYTHON% -c "import sphinx, sys; sys.argv[0] = 'sphinx-build'; sphinx.main()" +) + +if not defined BLURB if defined PYTHON ( + %PYTHON% -c "import blurb" > nul 2> nul + if errorlevel 1 ( + echo Installing blurb with %PYTHON% + %PYTHON% -m pip install blurb + if errorlevel 1 exit /B + ) + set BLURB=%PYTHON% -m blurb +) + +if not defined PYTHON set PYTHON=py +if not defined SPHINXBUILD set SPHINXBUILD=sphinx-build +if not defined BLURB set BLURB=blurb if "%1" NEQ "htmlhelp" goto :skiphhcsearch if exist "%HTMLHELP%" goto :skiphhcsearch @@ -36,7 +58,7 @@ if "%1" EQU "help" goto help if "%1" EQU "check" goto check if "%1" EQU "serve" goto serve if "%1" == "clean" ( - rmdir /q /s %BUILDDIR% + rmdir /q /s "%BUILDDIR%" goto end ) @@ -85,13 +107,28 @@ echo.be passed by setting the SPHINXOPTS environment variable. goto end :build +if not exist "%BUILDDIR%" mkdir "%BUILDDIR%" + +if exist ..\Misc\NEWS ( + echo.Copying Misc\NEWS to build\NEWS + copy ..\Misc\NEWS build\NEWS > nul +) else if exist ..\Misc\NEWS.D ( + if defined BLURB ( + echo.Merging Misc/NEWS with %BLURB% + %BLURB% merge -f build\NEWS + ) else ( + echo.No Misc/NEWS file and Blurb is not available. + exit /B 1 + ) +) + if NOT "%PAPER%" == "" ( set SPHINXOPTS=-D latex_elements.papersize=%PAPER% %SPHINXOPTS% ) -cmd /C %SPHINXBUILD% %SPHINXOPTS% -b%1 -dbuild\doctrees . %BUILDDIR%\%* +cmd /S /C "%SPHINXBUILD% %SPHINXOPTS% -b%1 -dbuild\doctrees . "%BUILDDIR%\%1" %2 %3 %4 %5 %6 %7 %8 %9" if "%1" EQU "htmlhelp" ( - cmd /C "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp + "%HTMLHELP%" "%BUILDDIR%\htmlhelp\python%DISTVERSION:.=%.hhp" rem hhc.exe seems to always exit with code 1, reset to 0 for less than 2 if not errorlevel 2 cmd /C exit /b 0 ) @@ -111,19 +148,19 @@ if NOT "%2" EQU "" ( ) cmd /C %this% html -if EXIST %BUILDDIR%\html\index.html ( - echo.Opening %BUILDDIR%\html\index.html in the default web browser... - start %BUILDDIR%\html\index.html +if EXIST "%BUILDDIR%\html\index.html" ( + echo.Opening "%BUILDDIR%\html\index.html" in the default web browser... + start "%BUILDDIR%\html\index.html" ) goto end :check -cmd /C %PYTHON% tools\rstlint.py -i tools +cmd /S /C "%PYTHON% tools\rstlint.py -i tools" goto end :serve -cmd /C %PYTHON% ..\Tools\scripts\serve.py %BUILDDIR%\html +cmd /S /C "%PYTHON% ..\Tools\scripts\serve.py "%BUILDDIR%\html"" goto end :end diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 7c140a3..230caf8 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1875,8 +1875,8 @@ Metaclass example ^^^^^^^^^^^^^^^^^ The potential uses for metaclasses are boundless. Some ideas that have been -explored include logging, interface checking, automatic delegation, automatic -property creation, proxies, frameworks, and automatic resource +explored include enum, logging, interface checking, automatic delegation, +automatic property creation, proxies, frameworks, and automatic resource locking/synchronization. Here is an example of a metaclass that uses an :class:`collections.OrderedDict` diff --git a/Doc/reference/import.rst b/Doc/reference/import.rst index d504f37..8cf16ca 100644 --- a/Doc/reference/import.rst +++ b/Doc/reference/import.rst @@ -965,7 +965,7 @@ References The import machinery has evolved considerably since Python's early days. The original `specification for packages -`_ is still available to read, +`_ is still available to read, although some details have changed since the writing of that document. The original specification for :data:`sys.meta_path` was :pep:`302`, with diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst index 7f9c664..c2fd2b7 100644 --- a/Doc/reference/lexical_analysis.rst +++ b/Doc/reference/lexical_analysis.rst @@ -313,7 +313,7 @@ The Unicode category codes mentioned above stand for: * *Nd* - decimal numbers * *Pc* - connector punctuations * *Other_ID_Start* - explicit list of characters in `PropList.txt - `_ to support backwards + `_ to support backwards compatibility * *Other_ID_Continue* - likewise @@ -676,6 +676,12 @@ Some examples of formatted string literals:: >>> value = decimal.Decimal("12.34567") >>> f"result: {value:{width}.{precision}}" # nested fields 'result: 12.35' + >>> today = datetime(year=2017, month=1, day=27) + >>> f"{today:%b %d, %Y}" # using date format specifier + 'January 27, 2017' + >>> number = 1024 + >>> f"{number:#0x}" # using integer format specifier + '0x400' A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the @@ -875,4 +881,4 @@ occurrence outside string literals and comments is an unconditional error: .. rubric:: Footnotes -.. [#] http://www.unicode.org/Public/8.0.0/ucd/NameAliases.txt +.. [#] http://www.unicode.org/Public/9.0.0/ucd/NameAliases.txt diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py index 865f2ed..8f507e4 100644 --- a/Doc/tools/extensions/pyspecific.py +++ b/Doc/tools/extensions/pyspecific.py @@ -15,6 +15,7 @@ from os import path from time import asctime from pprint import pformat from docutils.io import StringOutput +from docutils.parsers.rst import Directive from docutils.utils import new_document from docutils import nodes, utils @@ -23,7 +24,6 @@ from sphinx import addnodes from sphinx.builders import Builder from sphinx.locale import translators from sphinx.util.nodes import split_explicit_title -from sphinx.util.compat import Directive from sphinx.writers.html import HTMLTranslator from sphinx.writers.text import TextWriter from sphinx.writers.latex import LaTeXTranslator diff --git a/Doc/tools/static/switchers.js b/Doc/tools/static/switchers.js new file mode 100644 index 0000000..bd31fac --- /dev/null +++ b/Doc/tools/static/switchers.js @@ -0,0 +1,147 @@ +(function() { + 'use strict'; + + // Parses versions in URL segments like: + // "3", "dev", "release/2.7" or "3.6rc2" + var version_regexs = [ + '(?:\\d)', + '(?:\\d\\.\\d[\\w\\d\\.]*)', + '(?:dev)', + '(?:release/\\d.\\d[\\x\\d\\.]*)']; + + var all_versions = { + '3.7': 'dev (3.7)', + '3.6': '3.6', + '3.5': '3.5', + '3.4': '3.4', + '3.3': '3.3', + '2.7': '2.7', + }; + + var all_languages = { + 'en': 'English', + 'fr': 'French', + 'ja': 'Japanese', + }; + + function build_version_select(current_version, current_release) { + var buf = [''); + return buf.join(''); + } + + function build_language_select(current_language) { + var buf = [''); + return buf.join(''); + } + + function navigate_to_first_existing(urls) { + // Navigate to the first existing URL in urls. + var url = urls.shift(); + if (urls.length == 0) { + window.location.href = url; + return; + } + $.ajax({ + url: url, + success: function() { + window.location.href = url; + }, + error: function() { + navigate_to_first_existing(urls); + } + }); + } + + function on_version_switch() { + var selected_version = $(this).children('option:selected').attr('value') + '/'; + var url = window.location.href; + var current_language = language_segment_from_url(url); + var current_version = version_segment_in_url(url); + var new_url = url.replace('.org/' + current_language + current_version, + '.org/' + current_language + selected_version); + if (new_url != url) { + navigate_to_first_existing([ + new_url, + url.replace('.org/' + current_language + current_version, + '.org/' + selected_version), + 'https://docs.python.org/' + current_language + selected_version, + 'https://docs.python.org/' + selected_version, + 'https://docs.python.org/' + ]); + } + } + + function on_language_switch() { + var selected_language = $(this).children('option:selected').attr('value') + '/'; + var url = window.location.href; + var current_language = language_segment_from_url(url); + var current_version = version_segment_in_url(url); + if (selected_language == 'en/') // Special 'default' case for english. + selected_language = ''; + var new_url = url.replace('.org/' + current_language + current_version, + '.org/' + selected_language + current_version); + if (new_url != url) { + navigate_to_first_existing([ + new_url, + 'https://docs.python.org/' + ]); + } + } + + // Returns the path segment of the language as a string, like 'fr/' + // or '' if not found. + function language_segment_from_url(url) { + var language_regexp = '\.org/([a-z]{2}(?:-[a-z]{2})?/)'; + var match = url.match(language_regexp); + if (match !== null) + return match[1]; + return ''; + } + + // Returns the path segment of the version as a string, like '3.6/' + // or '' if not found. + function version_segment_in_url(url) { + var language_segment = '(?:[a-z]{2}(?:-[a-z]{2})?/)'; + var version_segment = '(?:(?:' + version_regexs.join('|') + ')/)'; + var version_regexp = '\\.org/' + language_segment + '?(' + version_segment + ')'; + var match = url.match(version_regexp); + if (match !== null) + return match[1]; + return '' + } + + $(document).ready(function() { + var release = DOCUMENTATION_OPTIONS.VERSION; + var language_segment = language_segment_from_url(window.location.href); + var current_language = language_segment.replace(/\/+$/g, '') || 'en'; + var version = release.substr(0, 3); + var version_select = build_version_select(version, release); + + $('.version_switcher_placeholder').html(version_select); + $('.version_switcher_placeholder select').bind('change', on_version_switch); + + var language_select = build_language_select(current_language); + + $('.language_switcher_placeholder').html(language_select); + $('.language_switcher_placeholder select').bind('change', on_language_switch); + }); +})(); diff --git a/Doc/tools/static/version_switch.js b/Doc/tools/static/version_switch.js deleted file mode 100644 index 8b36a61..0000000 --- a/Doc/tools/static/version_switch.js +++ /dev/null @@ -1,67 +0,0 @@ -(function() { - 'use strict'; - - var all_versions = { - '3.7': 'dev (3.7)', - '3.6': '3.6', - '3.5': '3.5', - '3.4': '3.4', - '3.3': '3.3', - '2.7': '2.7', - }; - - function build_select(current_version, current_release) { - var buf = [''); - return buf.join(''); - } - - function patch_url(url, new_version) { - var url_re = /\.org\/(\d|py3k|dev|((release\/)?\d\.\d[\w\d\.]*))\//, - new_url = url.replace(url_re, '.org/' + new_version + '/'); - - if (new_url == url && !new_url.match(url_re)) { - // python 2 url without version? - new_url = url.replace(/\.org\//, '.org/' + new_version + '/'); - } - return new_url; - } - - function on_switch() { - var selected = $(this).children('option:selected').attr('value'); - - var url = window.location.href, - new_url = patch_url(url, selected); - - if (new_url != url) { - // check beforehand if url exists, else redirect to version's start page - $.ajax({ - url: new_url, - success: function() { - window.location.href = new_url; - }, - error: function() { - window.location.href = 'https://docs.python.org/' + selected; - } - }); - } - } - - $(document).ready(function() { - var release = DOCUMENTATION_OPTIONS.VERSION; - var version = release.substr(0, 3); - var select = build_select(version, release); - - $('.version_switcher_placeholder').html(select); - $('.version_switcher_placeholder select').bind('change', on_switch); - }); -})(); diff --git a/Doc/tools/susp-ignored.csv b/Doc/tools/susp-ignored.csv index 2dc5404..6cd5a32 100644 --- a/Doc/tools/susp-ignored.csv +++ b/Doc/tools/susp-ignored.csv @@ -325,4 +325,3 @@ whatsnew/3.5,,:warning,'WARNING:root:warning\n' whatsnew/3.5,,::,>>> addr6 = ipaddress.IPv6Address('::1') whatsnew/3.5,,:root,ERROR:root:exception whatsnew/3.5,,:exception,ERROR:root:exception -whatsnew/changelog,,:version,import sys; I = version[:version.index(' ')] diff --git a/Doc/tools/templates/customsourcelink.html b/Doc/tools/templates/customsourcelink.html index 71d0bba..21af621 100644 --- a/Doc/tools/templates/customsourcelink.html +++ b/Doc/tools/templates/customsourcelink.html @@ -4,7 +4,7 @@
  • {% trans %}Report a Bug{% endtrans %}
  • - {{ _('Show Source') }}
  • diff --git a/Doc/tools/templates/download.html b/Doc/tools/templates/download.html index 3a05cb6..d49ebdd 100644 --- a/Doc/tools/templates/download.html +++ b/Doc/tools/templates/download.html @@ -18,23 +18,23 @@ in the table are the size of the download files in megabytes.

    - - + + - - + + - - + + - - + + - +
    FormatPacked as .zipPacked as .tar.bz2
    PDF (US-Letter paper size)Download (ca. 8 MB)Download (ca. 8 MB)Download (ca. 13 MB)Download (ca. 13 MB)
    PDF (A4 paper size)Download (ca. 8 MB)Download (ca. 8 MB)Download (ca. 13 MB)Download (ca. 13 MB)
    HTMLDownload (ca. 6 MB)Download (ca. 4 MB)Download (ca. 9 MB)Download (ca. 6 MB)
    Plain TextDownload (ca. 2 MB)Download (ca. 1.5 MB)Download (ca. 3 MB)Download (ca. 2 MB)
    EPUBDownload (ca. 4.5 MB)Download (ca. 5.5 MB)
    diff --git a/Doc/tools/templates/layout.html b/Doc/tools/templates/layout.html index 640d8b3..c210667 100644 --- a/Doc/tools/templates/layout.html +++ b/Doc/tools/templates/layout.html @@ -4,7 +4,8 @@ style="vertical-align: middle; margin-top: -1px"/>
  • Python{{ reldelim1 }}
  • - {%- if versionswitcher is defined %} + {%- if switchers is defined %} + {{ language or 'en' }} {{ release }} {% trans %}Documentation {% endtrans %}{{ reldelim1 }} {%- else %} @@ -41,7 +42,7 @@ {% if builder != "htmlhelp" %} {% if not embedded %}{% endif %} - {% if versionswitcher is defined and not embedded %}{% endif %} + {% if switchers is defined and not embedded %}{% endif %} {% if pagename == 'whatsnew/changelog' and not embedded %}