From: DongHun Kwak
Date: Tue, 8 Dec 2020 04:56:45 +0000 (+0900)
Subject: Imported Upstream version 3.7.8
X-Git-Tag: upstream/3.7.8^0
X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=f5bad5edb0f2902ff07c384d2c1c3e148e91d162;p=platform%2Fupstream%2Fpython3.git
Imported Upstream version 3.7.8
---
diff --git a/.azure-pipelines/ci.yml b/.azure-pipelines/ci.yml
index 7b3af5dc..b9038b98 100644
--- a/.azure-pipelines/ci.yml
+++ b/.azure-pipelines/ci.yml
@@ -61,7 +61,7 @@ jobs:
variables:
testRunTitle: '$(build.sourceBranchName)-linux'
testRunPlatform: linux
- openssl_version: 1.1.1d
+ openssl_version: 1.1.1g
steps:
- template: ./posix-steps.yml
@@ -118,7 +118,7 @@ jobs:
variables:
testRunTitle: '$(Build.SourceBranchName)-linux-coverage'
testRunPlatform: linux-coverage
- openssl_version: 1.1.1d
+ openssl_version: 1.1.1g
steps:
- template: ./posix-steps.yml
diff --git a/.azure-pipelines/pr.yml b/.azure-pipelines/pr.yml
index 73f4b96a..808b5f1c 100644
--- a/.azure-pipelines/pr.yml
+++ b/.azure-pipelines/pr.yml
@@ -61,7 +61,7 @@ jobs:
variables:
testRunTitle: '$(system.pullRequest.TargetBranch)-linux'
testRunPlatform: linux
- openssl_version: 1.1.1d
+ openssl_version: 1.1.1g
steps:
- template: ./posix-steps.yml
@@ -118,7 +118,7 @@ jobs:
variables:
testRunTitle: '$(Build.SourceBranchName)-linux-coverage'
testRunPlatform: linux-coverage
- openssl_version: 1.1.1d
+ openssl_version: 1.1.1g
steps:
- template: ./posix-steps.yml
diff --git a/Doc/Makefile b/Doc/Makefile
index 08013c0e..8a5e0307 100644
--- a/Doc/Makefile
+++ b/Doc/Makefile
@@ -127,7 +127,7 @@ clean:
venv:
$(PYTHON) -m venv $(VENVDIR)
- $(VENVDIR)/bin/python3 -m pip install -U Sphinx blurb
+ $(VENVDIR)/bin/python3 -m pip install -U Sphinx==2.3.1 blurb
@echo "The venv has been created in the $(VENVDIR) directory"
dist:
diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst
index 2f58149c..19147fe5 100644
--- a/Doc/c-api/exceptions.rst
+++ b/Doc/c-api/exceptions.rst
@@ -355,7 +355,7 @@ an error value).
.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
- :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
+ :exc:`ResourceWarning` and it passes *source* to :func:`warnings.WarningMessage`.
.. versionadded:: 3.6
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index e4aad1f6..7c76ed87 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -162,6 +162,39 @@ complete listing.
.. versionadded:: 3.4
+.. c:macro:: PyDoc_STRVAR(name, str)
+
+ Creates a variable with name ``name`` that can be used in docstrings.
+ If Python is built without docstrings, the value will be empty.
+
+ Use :c:macro:`PyDoc_STRVAR` for docstrings to support building
+ Python without docstrings, as specified in :pep:`7`.
+
+ Example::
+
+ PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
+
+ static PyMethodDef deque_methods[] = {
+ // ...
+ {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
+ // ...
+ }
+
+.. c:macro:: PyDoc_STR(str)
+
+ Creates a docstring for the given input string or an empty string
+ if docstrings are disabled.
+
+ Use :c:macro:`PyDoc_STR` in specifying docstrings to support
+ building Python without docstrings, as specified in :pep:`7`.
+
+ Example::
+
+ static PyMethodDef pysqlite_row_methods[] = {
+ {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
+ PyDoc_STR("Returns the keys of the row.")},
+ {NULL, NULL}
+ };
.. _api-objects:
diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst
index a06e791e..c85bf17c 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -153,7 +153,7 @@ or request "multi-phase initialization" by returning the definition struct itsel
.. c:member:: const char *m_doc
Docstring for the module; usually a docstring variable created with
- :c:func:`PyDoc_STRVAR` is used.
+ :c:macro:`PyDoc_STRVAR` is used.
.. c:member:: Py_ssize_t m_size
diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst
index d81dc938..179efc42 100644
--- a/Doc/c-api/object.rst
+++ b/Doc/c-api/object.rst
@@ -128,7 +128,7 @@ Object Protocol
.. versionadded:: 3.3
-.. c:function:: int PyObject_GenericSetDict(PyObject *o, void *context)
+.. c:function:: int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
A generic implementation for the setter of a ``__dict__`` descriptor. This
implementation does not allow the dictionary to be deleted.
diff --git a/Doc/data/refcounts.dat b/Doc/data/refcounts.dat
index ec8094ef..39061e2c 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -1655,7 +1655,8 @@ PyObject_GenericSetAttr:PyObject*:name:0:
PyObject_GenericSetAttr:PyObject*:value:+1:
PyObject_GenericSetDict:int:::
-PyObject_GenericSetDict:PyObject*:o:+1:
+PyObject_GenericSetDict:PyObject*:o:0:
+PyObject_GenericSetDict:PyObject*:value:+1:
PyObject_GenericSetDict:void*:context::
PyObject_GetAttr:PyObject*::+1:
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index 270f57d8..604c8ff5 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -1501,8 +1501,8 @@ to uppercase::
Here the ``UpperOut`` class redefines the ``write()`` method to convert the
argument string to uppercase before calling the underlying
-``self.__outfile.write()`` method. All other methods are delegated to the
-underlying ``self.__outfile`` object. The delegation is accomplished via the
+``self._outfile.write()`` method. All other methods are delegated to the
+underlying ``self._outfile`` object. The delegation is accomplished via the
``__getattr__`` method; consult :ref:`the language reference `
for more information about controlling attribute access.
diff --git a/Doc/howto/sockets.rst b/Doc/howto/sockets.rst
index bc71d85a..b5c2152e 100644
--- a/Doc/howto/sockets.rst
+++ b/Doc/howto/sockets.rst
@@ -319,7 +319,7 @@ inside-out.
In Python, you use ``socket.setblocking(0)`` to make it non-blocking. In C, it's
more complex, (for one thing, you'll need to choose between the BSD flavor
-``O_NONBLOCK`` and the almost indistinguishable Posix flavor ``O_NDELAY``, which
+``O_NONBLOCK`` and the almost indistinguishable POSIX flavor ``O_NDELAY``, which
is completely different from ``TCP_NODELAY``), but it's the exact same idea. You
do this after creating the socket, but before using it. (Actually, if you're
nuts, you can switch back and forth.)
diff --git a/Doc/install/index.rst b/Doc/install/index.rst
index f6a8cd68..b82c1b23 100644
--- a/Doc/install/index.rst
+++ b/Doc/install/index.rst
@@ -578,7 +578,7 @@ scripts will wind up in :file:`/usr/local/python/bin`. If you want them in
python setup.py install --install-scripts=/usr/local/bin
-(This performs an installation using the "prefix scheme," where the prefix is
+(This performs an installation using the "prefix scheme", where the prefix is
whatever your Python interpreter was installed with--- :file:`/usr/local/python`
in this case.)
diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index 6d6ae6de..1dddad82 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -244,7 +244,7 @@ and classes for traversing abstract syntax trees:
value=Name(id='data', ctx=Load()),
slice=Index(value=Str(s=node.id)),
ctx=node.ctx
- ), node)
+ )
Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the :meth:`generic_visit`
diff --git a/Doc/library/code.rst b/Doc/library/code.rst
index 6708079f..538e5afc 100644
--- a/Doc/library/code.rst
+++ b/Doc/library/code.rst
@@ -56,8 +56,8 @@ build applications which provide an interactive interpreter prompt.
*source* is the source string; *filename* is the optional filename from which
source was read, defaulting to ``''``; and *symbol* is the optional
- grammar start symbol, which should be either ``'single'`` (the default) or
- ``'eval'``.
+ grammar start symbol, which should be ``'single'`` (the default), ``'eval'``
+ or ``'exec'``.
Returns a code object (the same as ``compile(source, filename, symbol)``) if the
command is complete and valid; ``None`` if the command is incomplete; raises
diff --git a/Doc/library/codeop.rst b/Doc/library/codeop.rst
index a52d2c62..c66b9d3e 100644
--- a/Doc/library/codeop.rst
+++ b/Doc/library/codeop.rst
@@ -43,8 +43,9 @@ To do just the former:
:exc:`OverflowError` or :exc:`ValueError` if there is an invalid literal.
The *symbol* argument determines whether *source* is compiled as a statement
- (``'single'``, the default) or as an :term:`expression` (``'eval'``). Any
- other value will cause :exc:`ValueError` to be raised.
+ (``'single'``, the default), as a sequence of statements (``'exec'``) or
+ as an :term:`expression` (``'eval'``). Any other value will
+ cause :exc:`ValueError` to be raised.
.. note::
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 049537ef..bd4e775b 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -161,7 +161,8 @@ The :mod:`csv` module defines the following classes:
If a row has more fields than fieldnames, the remaining data is put in a
list and stored with the fieldname specified by *restkey* (which defaults
to ``None``). If a non-blank row has fewer fields than fieldnames, the
- missing values are filled-in with ``None``.
+ missing values are filled-in with the value of *restval* (which defaults
+ to ``None``).
All other optional or keyword arguments are passed to the underlying
:class:`reader` instance.
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst
index 37258d4e..10edcac7 100644
--- a/Doc/library/dataclasses.rst
+++ b/Doc/library/dataclasses.rst
@@ -19,6 +19,8 @@ in :pep:`557`.
The member variables to use in these generated methods are defined
using :pep:`526` type annotations. For example this code::
+ from dataclasses import dataclass
+
@dataclass
class InventoryItem:
'''Class for keeping track of an item in inventory.'''
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index 3dda35fb..8169bd35 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -2130,67 +2130,17 @@ Q. Is the CPython implementation fast for large numbers?
A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of
the decimal module integrate the high speed `libmpdec
`_ library for
-arbitrary precision correctly-rounded decimal floating point arithmetic [#]_.
+arbitrary precision correctly-rounded decimal floating point arithmetic.
``libmpdec`` uses `Karatsuba multiplication
`_
for medium-sized numbers and the `Number Theoretic Transform
`_
-for very large numbers.
+for very large numbers. However, to realize this performance gain, the
+context needs to be set for unrounded calculations.
-The context must be adapted for exact arbitrary precision arithmetic. :attr:`Emin`
-and :attr:`Emax` should always be set to the maximum values, :attr:`clamp`
-should always be 0 (the default). Setting :attr:`prec` requires some care.
+ >>> c = getcontext()
+ >>> c.prec = MAX_PREC
+ >>> c.Emax = MAX_EMAX
+ >>> c.Emin = MIN_EMIN
-The easiest approach for trying out bignum arithmetic is to use the maximum
-value for :attr:`prec` as well [#]_::
-
- >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
- >>> x = Decimal(2) ** 256
- >>> x / 128
- Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
-
-
-For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms and
-the available memory will be insufficient::
-
- >>> Decimal(1) / 3
- Traceback (most recent call last):
- File "", line 1, in
- MemoryError
-
-On systems with overallocation (e.g. Linux), a more sophisticated approach is to
-adjust :attr:`prec` to the amount of available RAM. Suppose that you have 8GB of
-RAM and expect 10 simultaneous operands using a maximum of 500MB each::
-
- >>> import sys
- >>>
- >>> # Maximum number of digits for a single operand using 500MB in 8-byte words
- >>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
- >>> maxdigits = 19 * ((500 * 1024**2) // 8)
- >>>
- >>> # Check that this works:
- >>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
- >>> c.traps[Inexact] = True
- >>> setcontext(c)
- >>>
- >>> # Fill the available precision with nines:
- >>> x = Decimal(0).logical_invert() * 9
- >>> sys.getsizeof(x)
- 524288112
- >>> x + 2
- Traceback (most recent call last):
- File "", line 1, in
- decimal.Inexact: []
-
-In general (and especially on systems without overallocation), it is recommended
-to estimate even tighter bounds and set the :attr:`Inexact` trap if all calculations
-are expected to be exact.
-
-
-.. [#]
- .. versionadded:: 3.3
-
-.. [#]
- .. versionchanged:: 3.9
- This approach now works for all exact results except for non-integer powers.
- Also backported to 3.7 and 3.8.
+.. versionadded:: 3.3
\ No newline at end of file
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 5c29c61a..239cf74a 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -244,7 +244,7 @@ operation is being performed, so the intermediate analysis object isn't useful:
.. function:: findlabels(code)
- Detect all offsets in the code object *code* which are jump targets, and
+ Detect all offsets in the raw compiled bytecode string *code* which are jump targets, and
return a list of these offsets.
@@ -835,9 +835,9 @@ All of the following opcodes use their arguments.
.. opcode:: BUILD_CONST_KEY_MAP (count)
- The version of :opcode:`BUILD_MAP` specialized for constant keys. *count*
- values are consumed from the stack. The top element on the stack contains
- a tuple of keys.
+ The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the
+ top element on the stack which contains a tuple of keys, then starting from
+ ``TOS1``, pops *count* values to form values in the built dictionary.
.. versionadded:: 3.6
@@ -1142,7 +1142,7 @@ All of the following opcodes use their arguments.
.. versionadded:: 3.7
-.. opcode:: MAKE_FUNCTION (argc)
+.. opcode:: MAKE_FUNCTION (flags)
Pushes a new function object on the stack. From bottom to top, the consumed
stack must consist of values if the argument carries a specified flag value
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index 38221199..e340f3ba 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -273,6 +273,10 @@ overridden::
the next :class:`int` in sequence with the last :class:`int` provided, but
the way it does this is an implementation detail and may change.
+.. note::
+
+ The :meth:`_generate_next_value_` method must be defined before any members.
+
Iteration
---------
diff --git a/Doc/library/idle.rst b/Doc/library/idle.rst
index fd6e3095..b1192e7b 100644
--- a/Doc/library/idle.rst
+++ b/Doc/library/idle.rst
@@ -142,7 +142,9 @@ Replace...
Open a search-and-replace dialog.
Go to Line
- Move cursor to the line number requested and make that line visible.
+ Move the cursor to the beginning of the line requested and make that
+ line visible. A request past the end of the file goes to the end.
+ Clear any selection and update the line and column status.
Show Completions
Open a scrollable list allowing selection of keywords and attributes. See
diff --git a/Doc/library/imp.rst b/Doc/library/imp.rst
index f5ad8c72..121a730e 100644
--- a/Doc/library/imp.rst
+++ b/Doc/library/imp.rst
@@ -8,7 +8,7 @@
**Source code:** :source:`Lib/imp.py`
.. deprecated:: 3.4
- The :mod:`imp` package is pending deprecation in favor of :mod:`importlib`.
+ The :mod:`imp` module is deprecated in favor of :mod:`importlib`.
.. index:: statement: import
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index 0057eab3..79de0a06 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -1029,6 +1029,10 @@ find and load modules.
Only class methods are defined by this class to alleviate the need for
instantiation.
+ .. versionchanged:: 3.4
+ Gained :meth:`~Loader.create_module` and :meth:`~Loader.exec_module`
+ methods.
+
.. class:: WindowsRegistryFinder
diff --git a/Doc/library/keyword.rst b/Doc/library/keyword.rst
index 3768df96..acec45cd 100644
--- a/Doc/library/keyword.rst
+++ b/Doc/library/keyword.rst
@@ -8,16 +8,17 @@
--------------
-This module allows a Python program to determine if a string is a keyword.
+This module allows a Python program to determine if a string is a
+:ref:`keyword `.
.. function:: iskeyword(s)
- Return ``True`` if *s* is a Python keyword.
+ Return ``True`` if *s* is a Python :ref:`keyword `.
.. data:: kwlist
- 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.
+ Sequence containing all the :ref:`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.
diff --git a/Doc/library/mailcap.rst b/Doc/library/mailcap.rst
index 896afd1d..bf9639bd 100644
--- a/Doc/library/mailcap.rst
+++ b/Doc/library/mailcap.rst
@@ -18,7 +18,7 @@ belonging to a temporary file) and the :program:`xmpeg` program can be
automatically started to view the file.
The mailcap format is documented in :rfc:`1524`, "A User Agent Configuration
-Mechanism For Multimedia Mail Format Information," but is not an Internet
+Mechanism For Multimedia Mail Format Information", but is not an Internet
standard. However, mailcap files are supported on most Unix systems.
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index 6fd509a0..1b850ebc 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -429,7 +429,8 @@ process which created it.
>>> def f(x):
... return x*x
...
- >>> p.map(f, [1,2,3])
+ >>> with p:
+ ... p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
@@ -2100,6 +2101,16 @@ with the :class:`Pool` class.
Note that the methods of the pool object should only be called by
the process which created the pool.
+ .. warning::
+ :class:`multiprocessing.pool` objects have internal resources that need to be
+ properly managed (like any other resource) by using the pool as a context manager
+ or by calling :meth:`close` and :meth:`terminate` manually. Failure to do this
+ can lead to the process hanging on finalization.
+
+ Note that is **not correct** to rely on the garbage colletor to destroy the pool
+ as CPython does not assure that the finalizer of the pool will be called
+ (see :meth:`object.__del__` for more information).
+
.. versionadded:: 3.2
*maxtasksperchild*
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index e23500d4..685d5608 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -3765,28 +3765,36 @@ used to determine the disposition of a process.
Return ``True`` if a core dump was generated for the process, otherwise
return ``False``.
+ This function should be employed only if :func:`WIFSIGNALED` is true.
+
.. availability:: Unix.
.. function:: WIFCONTINUED(status)
- Return ``True`` if the process has been continued from a job control stop,
- otherwise return ``False``.
+ Return ``True`` if a stopped child has been resumed by delivery of
+ :data:`~signal.SIGCONT` (if the process has been continued from a job
+ control stop), otherwise return ``False``.
+
+ See :data:`WCONTINUED` option.
.. availability:: Unix.
.. function:: WIFSTOPPED(status)
- Return ``True`` if the process has been stopped, otherwise return
- ``False``.
+ Return ``True`` if the process was stopped by delivery of a signal,
+ otherwise return ``False``.
- .. availability:: Unix.
+ :func:`WIFSTOPPED` only returns ``True`` if the :func:`waitpid` call was
+ done using :data:`WUNTRACED` option or when the process is being traced (see
+ :manpage:`ptrace(2)`).
+ .. availability:: Unix.
.. function:: WIFSIGNALED(status)
- Return ``True`` if the process exited due to a signal, otherwise return
+ Return ``True`` if the process was terminated by a signal, otherwise return
``False``.
.. availability:: Unix.
@@ -3794,7 +3802,8 @@ used to determine the disposition of a process.
.. function:: WIFEXITED(status)
- Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
+ Return ``True`` if the process exited terminated normally, that is,
+ by calling ``exit()`` or ``_exit()``, or by returning from ``main()``;
otherwise return ``False``.
.. availability:: Unix.
@@ -3802,8 +3811,9 @@ used to determine the disposition of a process.
.. function:: WEXITSTATUS(status)
- If ``WIFEXITED(status)`` is true, return the integer parameter to the
- :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
+ Return the process exit status.
+
+ This function should be employed only if :func:`WIFEXITED` is true.
.. availability:: Unix.
@@ -3812,12 +3822,16 @@ used to determine the disposition of a process.
Return the signal which caused the process to stop.
+ This function should be employed only if :func:`WIFSTOPPED` is true.
+
.. availability:: Unix.
.. function:: WTERMSIG(status)
- Return the signal which caused the process to exit.
+ Return the number of the signal that caused the process to terminate.
+
+ This function should be employed only if :func:`WIFSIGNALED` is true.
.. availability:: Unix.
diff --git a/Doc/library/othergui.rst b/Doc/library/othergui.rst
index 4548459f..48c1f275 100644
--- a/Doc/library/othergui.rst
+++ b/Doc/library/othergui.rst
@@ -30,10 +30,11 @@ available for Python:
for generating bindings for C++ libraries as Python classes, and
is specifically designed for Python.
- `PySide `_
- PySide is a newer binding to the Qt toolkit, provided by Nokia.
- Compared to PyQt, its licensing scheme is friendlier to non-open source
- applications.
+ `PySide2 `_
+ Also known as the Qt for Python project, PySide2 is a newer binding to the
+ Qt toolkit. It is provided by The Qt Company and aims to provide a
+ complete port of PySide to Qt 5. Compared to PyQt, its licensing scheme is
+ friendlier to non-open source applications.
`wxPython `_
wxPython is a cross-platform GUI toolkit for Python that is built around
@@ -47,7 +48,7 @@ available for Python:
an XML-based resource format and more, including an ever growing library
of user-contributed modules.
-PyGTK, PyQt, and wxPython, all have a modern look and feel and more
+PyGTK, PyQt, PySide2, and wxPython, all have a modern look and feel and more
widgets than Tkinter. In addition, there are many other GUI toolkits for
Python, both cross-platform, and platform-specific. See the `GUI Programming
`_ page in the Python Wiki for a
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst
index 9ed5d9da..04491742 100644
--- a/Doc/library/pathlib.rst
+++ b/Doc/library/pathlib.rst
@@ -515,8 +515,10 @@ Pure paths provide the following methods and properties:
>>> PurePath('a/b.py').match('/*.py')
False
- As with other methods, case-sensitivity is observed::
+ As with other methods, case-sensitivity follows platform defaults::
+ >>> PurePosixPath('b.py').match('*.PY')
+ False
>>> PureWindowsPath('b.py').match('*.PY')
True
diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst
index f741976c..25044899 100644
--- a/Doc/library/pickle.rst
+++ b/Doc/library/pickle.rst
@@ -242,10 +242,10 @@ process more convenient:
instances of :class:`~datetime.datetime`, :class:`~datetime.date` and
:class:`~datetime.time` pickled by Python 2.
-.. function:: loads(bytes_object, \*, fix_imports=True, encoding="ASCII", errors="strict")
+.. function:: loads(data, \*, fix_imports=True, encoding="ASCII", errors="strict")
Return the reconstituted object hierarchy of the pickled representation
- *bytes_object* of an object.
+ *data* of an object. *data* must be a :term:`bytes-like object`.
The protocol version of the pickle is detected automatically, so no
protocol argument is needed. Bytes past the pickled representation
@@ -562,9 +562,9 @@ the methods :meth:`__getstate__` and :meth:`__setstate__`.
At unpickling time, some methods like :meth:`__getattr__`,
:meth:`__getattribute__`, or :meth:`__setattr__` may be called upon the
instance. In case those methods rely on some internal invariant being
- true, the type should implement :meth:`__getnewargs__` or
- :meth:`__getnewargs_ex__` to establish such an invariant; otherwise,
- neither :meth:`__new__` nor :meth:`__init__` will be called.
+ true, the type should implement :meth:`__new__` to establish such an
+ invariant, as :meth:`__init__` is not called when unpickling an
+ instance.
.. index:: pair: copy; protocol
diff --git a/Doc/library/pprint.rst b/Doc/library/pprint.rst
index deadf182..3167c9f0 100644
--- a/Doc/library/pprint.rst
+++ b/Doc/library/pprint.rst
@@ -120,7 +120,7 @@ The :mod:`pprint` module also provides several shortcut functions:
.. index:: builtin: eval
- Determine if the formatted representation of *object* is "readable," or can be
+ Determine if the formatted representation of *object* is "readable", or can be
used to reconstruct the value using :func:`eval`. This always returns ``False``
for recursive objects.
diff --git a/Doc/library/select.rst b/Doc/library/select.rst
index 7d65363e..0bc8800d 100644
--- a/Doc/library/select.rst
+++ b/Doc/library/select.rst
@@ -117,7 +117,7 @@ The module defines the following:
.. function:: select(rlist, wlist, xlist[, timeout])
This is a straightforward interface to the Unix :c:func:`select` system call.
- The first three arguments are sequences of 'waitable objects': either
+ The first three arguments are iterables of 'waitable objects': either
integers representing file descriptors or objects with a parameterless method
named :meth:`~io.IOBase.fileno` returning such an integer:
@@ -126,7 +126,7 @@ The module defines the following:
* *xlist*: wait for an "exceptional condition" (see the manual page for what
your system considers such a condition)
- Empty sequences are allowed, but acceptance of three empty sequences is
+ Empty iterables are allowed, but acceptance of three empty iterables is
platform-dependent. (It is known to work on Unix but not on Windows.) The
optional *timeout* argument specifies a time-out as a floating point number
in seconds. When the *timeout* argument is omitted the function blocks until
@@ -141,7 +141,7 @@ The module defines the following:
single: socket() (in module socket)
single: popen() (in module os)
- Among the acceptable object types in the sequences are Python :term:`file
+ Among the acceptable object types in the iterables are Python :term:`file
objects ` (e.g. ``sys.stdin``, or objects returned by
:func:`open` or :func:`os.popen`), socket objects returned by
:func:`socket.socket`. You may also define a :dfn:`wrapper` class yourself,
diff --git a/Doc/library/shutil.rst b/Doc/library/shutil.rst
index 12e69a4e..79950585 100644
--- a/Doc/library/shutil.rst
+++ b/Doc/library/shutil.rst
@@ -477,12 +477,14 @@ provided. They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
available), or "xztar" (if the :mod:`lzma` module is available).
*root_dir* is a directory that will be the root directory of the
- archive; for example, we typically chdir into *root_dir* before creating the
- archive.
+ archive, all paths in the archive will be relative to it; for example,
+ we typically chdir into *root_dir* before creating the archive.
*base_dir* is the directory where we start archiving from;
i.e. *base_dir* will be the common prefix of all files and
- directories in the archive.
+ directories in the archive. *base_dir* must be given relative
+ to *root_dir*. See :ref:`shutil-archiving-example-with-basedir` for how to
+ use *base_dir* and *root_dir* together.
*root_dir* and *base_dir* both default to the current directory.
@@ -626,6 +628,48 @@ The resulting archive contains:
-rw-r--r-- tarek/staff 37192 2010-02-06 18:23:10 ./known_hosts
+.. _shutil-archiving-example-with-basedir:
+
+Archiving example with *base_dir*
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+In this example, similar to the `one above `_,
+we show how to use :func:`make_archive`, but this time with the usage of
+*base_dir*. We now have the following directory structure:
+
+.. code-block:: shell-session
+
+ $ tree tmp
+ tmp
+ âââ root
+ âââ structure
+ âââ content
+ âââ please_add.txt
+ âââ do_not_add.txt
+
+In the final archive, :file:`please_add.txt` should be included, but
+:file:`do_not_add.txt` should not. Therefore we use the following::
+
+ >>> from shutil import make_archive
+ >>> import os
+ >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
+ >>> make_archive(
+ ... archive_name,
+ ... 'tar',
+ ... root_dir='tmp/root',
+ ... base_dir='structure/content',
+ ... )
+ '/Users/tarek/my_archive.tar'
+
+Listing the files in the resulting archive gives us:
+
+.. code-block:: shell-session
+
+ $ python -m tarfile -l /Users/tarek/myarchive.tar
+ structure/content/
+ structure/content/please_add.txt
+
+
Querying the size of the output terminal
----------------------------------------
diff --git a/Doc/library/signal.rst b/Doc/library/signal.rst
index 75008118..7f48f8c2 100644
--- a/Doc/library/signal.rst
+++ b/Doc/library/signal.rst
@@ -91,6 +91,110 @@ The variables defined in the :mod:`signal` module are:
signal.
+.. data:: SIGABRT
+
+ Abort signal from :manpage:`abort(3)`.
+
+.. data:: SIGALRM
+
+ Timer signal from :manpage:`alarm(2)`.
+
+ .. availability:: Unix.
+
+.. data:: SIGBREAK
+
+ Interrupt from keyboard (CTRL + BREAK).
+
+ .. availability:: Windows.
+
+.. data:: SIGBUS
+
+ Bus error (bad memory access).
+
+ .. availability:: Unix.
+
+.. data:: SIGCHLD
+
+ Child process stopped or terminated.
+
+ .. availability:: Windows.
+
+.. data:: SIGCLD
+
+ Alias to :data:`SIGCHLD`.
+
+.. data:: SIGCONT
+
+ Continue the process if it is currently stopped
+
+ .. availability:: Unix.
+
+.. data:: SIGFPE
+
+ Floating-point exception. For example, division by zero.
+
+ .. seealso::
+ :exc:`ZeroDivisionError` is raised when the second argument of a division
+ or modulo operation is zero.
+
+.. data:: SIGHUP
+
+ Hangup detected on controlling terminal or death of controlling process.
+
+ .. availability:: Unix.
+
+.. data:: SIGILL
+
+ Illegal instruction.
+
+.. data:: SIGINT
+
+ Interrupt from keyboard (CTRL + C).
+
+ Default action is to raise :exc:`KeyboardInterrupt`.
+
+.. data:: SIGKILL
+
+ Kill signal.
+
+ It cannot be caught, blocked, or ignored.
+
+ .. availability:: Unix.
+
+.. data:: SIGPIPE
+
+ Broken pipe: write to pipe with no readers.
+
+ Default action is to ignore the signal.
+
+ .. availability:: Unix.
+
+.. data:: SIGSEGV
+
+ Segmentation fault: invalid memory reference.
+
+.. data:: SIGTERM
+
+ Termination signal.
+
+.. data:: SIGUSR1
+
+ User-defined signal 1.
+
+ .. availability:: Unix.
+
+.. data:: SIGUSR2
+
+ User-defined signal 2.
+
+ .. availability:: Unix.
+
+.. data:: SIGWINCH
+
+ Window resize signal.
+
+ .. availability:: Unix.
+
.. data:: SIG*
All the signal numbers are defined symbolically. For example, the hangup signal
@@ -270,6 +374,8 @@ The :mod:`signal` module defines the following functions:
For example, ``signal.pthread_sigmask(signal.SIG_BLOCK, [])`` reads the
signal mask of the calling thread.
+ :data:`SIGKILL` and :data:`SIGSTOP` cannot be blocked.
+
.. availability:: Unix. See the man page :manpage:`sigprocmask(3)` and
:manpage:`pthread_sigmask(3)` for further information.
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index 7c8c8d52..232c0616 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -237,6 +237,8 @@ Server Objects
.. method:: shutdown()
Tell the :meth:`serve_forever` loop to stop and wait until it does.
+ :meth:`shutdown` must be called while :meth:`serve_forever` is running in a
+ different thread otherwise it will deadlock.
.. method:: server_close()
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index e20b4b3d..8609be2c 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -165,9 +165,10 @@ Module functions and constants
that 'mytype' is the type of the column. It will try to find an entry of
'mytype' in the converters dictionary and then use the converter function found
there to return the value. The column name found in :attr:`Cursor.description`
- is only the first word of the column name, i. e. if you use something like
- ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
- first blank for the column name: the column name would simply be "x".
+ does not include the type, i. e. if you use something like
+ ``'as "Expiration date [datetime]"'`` in your SQL, then we will parse out
+ everything until the first ``'['`` for the column name and strip
+ the preceeding space: the column name would simply be "Expiration date".
.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index 5aff697b..0646b30f 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -42,7 +42,7 @@ This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
:class:`socket.socket` type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL. It supports
additional methods such as :meth:`getpeercert`, which retrieves the
-certificate of the other side of the connection, and :meth:`cipher`,which
+certificate of the other side of the connection, and :meth:`cipher`, which
retrieves the cipher being used for the secure connection.
For more sophisticated applications, the :class:`ssl.SSLContext` class
@@ -2235,7 +2235,7 @@ Visual inspection shows that the certificate does identify the desired service
(('postalCode', '03894-4801'),),
(('countryName', 'US'),),
(('stateOrProvinceName', 'NH'),),
- (('localityName', 'Wolfeboro,'),),
+ (('localityName', 'Wolfeboro'),),
(('organizationName', 'Python Software Foundation'),),
(('commonName', 'www.python.org'),)),
'subjectAltName': (('DNS', 'www.python.org'),
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index c4c4ccd7..c35cb2e1 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -436,12 +436,10 @@ Notes:
Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
(2)
- A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
- without overflow check.
+ A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``.
(3)
- A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
- overflow check.
+ A right shift by *n* bits is equivalent to floor division by ``pow(2, n)``.
(4)
Performing these calculations with at least one extra sign extension bit in
diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst
index 69737820..9f2a0566 100644
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -40,7 +40,7 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\
capture_output=False, shell=False, cwd=None, timeout=None, \
check=False, encoding=None, errors=None, text=None, env=None, \
- universal_newlines=None)
+ universal_newlines=None, **other_popen_kwargs)
Run the command described by *args*. Wait for command to complete, then
return a :class:`CompletedProcess` instance.
@@ -711,14 +711,14 @@ Instances of the :class:`Popen` class have the following methods:
.. method:: Popen.terminate()
- Stop the child. On Posix OSs the method sends SIGTERM to the
+ Stop the child. On POSIX OSs the method sends SIGTERM to the
child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
to stop the child.
.. method:: Popen.kill()
- Kills the child. On Posix OSs the function sends SIGKILL to the child.
+ Kills the child. On POSIX OSs the function sends SIGKILL to the child.
On Windows :meth:`kill` is an alias for :meth:`terminate`.
@@ -1005,7 +1005,8 @@ 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, cwd=None, timeout=None)
+.. function:: call(args, *, stdin=None, stdout=None, stderr=None, \
+ shell=False, cwd=None, timeout=None, **other_popen_kwargs)
Run the command described by *args*. Wait for command to complete, then
return the :attr:`~Popen.returncode` attribute.
@@ -1031,7 +1032,9 @@ calls these functions.
.. versionchanged:: 3.3
*timeout* was added.
-.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None)
+.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, \
+ shell=False, cwd=None, timeout=None, \
+ **other_popen_kwargs)
Run command with arguments. Wait for command to complete. If the return
code was zero then return, otherwise raise :exc:`CalledProcessError`. The
@@ -1062,7 +1065,8 @@ calls these functions.
.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \
cwd=None, encoding=None, errors=None, \
- universal_newlines=None, timeout=None, text=None)
+ universal_newlines=None, timeout=None, text=None, \
+ **other_popen_kwargs)
Run command with arguments and return its output.
diff --git a/Doc/library/sysconfig.rst b/Doc/library/sysconfig.rst
index b5a1da80..78a1dfce 100644
--- a/Doc/library/sysconfig.rst
+++ b/Doc/library/sysconfig.rst
@@ -74,12 +74,12 @@ places.
Python currently supports seven schemes:
-- *posix_prefix*: scheme for Posix platforms like Linux or Mac OS X. This is
+- *posix_prefix*: scheme for POSIX platforms like Linux or Mac OS X. This is
the default scheme used when Python or a component is installed.
-- *posix_home*: scheme for Posix platforms used when a *home* option is used
+- *posix_home*: scheme for POSIX platforms used when a *home* option is used
upon installation. This scheme is used when a component is installed through
Distutils with a specific home prefix.
-- *posix_user*: scheme for Posix platforms used when a component is installed
+- *posix_user*: scheme for POSIX platforms used when a component is installed
through Distutils and the *user* option is used. This scheme defines paths
located under the user home directory.
- *nt*: scheme for NT platforms like Windows.
diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst
index 9cd07158..aa284416 100644
--- a/Doc/library/tarfile.rst
+++ b/Doc/library/tarfile.rst
@@ -779,7 +779,7 @@ How to read a gzip compressed tar archive and display some member information::
import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
- print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
+ print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
if tarinfo.isreg():
print("a regular file.")
elif tarinfo.isdir():
diff --git a/Doc/library/textwrap.rst b/Doc/library/textwrap.rst
index 0f11ef40..16837104 100644
--- a/Doc/library/textwrap.rst
+++ b/Doc/library/textwrap.rst
@@ -239,7 +239,7 @@ hyphenated words; only then will long words be broken if necessary, unless
:attr:`fix_sentence_endings` is false by default.
Since the sentence detection algorithm relies on ``string.lowercase`` for
- the definition of "lowercase letter," and a convention of using two spaces
+ the definition of "lowercase letter", and a convention of using two spaces
after a period to separate sentences on the same line, it is specific to
English-language texts.
diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst
index ef7a4e40..46fa62c1 100644
--- a/Doc/library/timeit.rst
+++ b/Doc/library/timeit.rst
@@ -251,7 +251,8 @@ quotes and using leading spaces. Multiple :option:`-s` options are treated
similarly.
If :option:`-n` is not given, a suitable number of loops is calculated by trying
-successive powers of 10 until the total time is at least 0.2 seconds.
+increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the total
+time is at least 0.2 seconds.
:func:`default_timer` measurements can be affected by other programs running on
the same machine, so the best thing to do when accurate timing is necessary is
diff --git a/Doc/library/tokenize.rst b/Doc/library/tokenize.rst
index 4dd56f9e..2f6cf290 100644
--- a/Doc/library/tokenize.rst
+++ b/Doc/library/tokenize.rst
@@ -13,7 +13,7 @@
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
+as well, making it useful for implementing "pretty-printers", including
colorizers for on-screen displays.
To simplify token stream handling, all :ref:`operator ` and
diff --git a/Doc/library/tracemalloc.rst b/Doc/library/tracemalloc.rst
index 2d327c02..000c0ee9 100644
--- a/Doc/library/tracemalloc.rst
+++ b/Doc/library/tracemalloc.rst
@@ -202,10 +202,8 @@ ignoring ```` and ```` files::
print("Top %s lines" % limit)
for index, stat in enumerate(top_stats[:limit], 1):
frame = stat.traceback[0]
- # replace "/path/to/module/file.py" with "module/file.py"
- filename = os.sep.join(frame.filename.split(os.sep)[-2:])
print("#%s: %s:%s: %.1f KiB"
- % (index, filename, frame.lineno, stat.size / 1024))
+ % (index, frame.filename, frame.lineno, stat.size / 1024))
line = linecache.getline(frame.filename, frame.lineno).strip()
if line:
print(' %s' % line)
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
index 0cd6918b..3cc0665d 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -910,10 +910,10 @@ Test cases
.. versionadded:: 3.1
- .. method:: assertIn(first, second, msg=None)
- assertNotIn(first, second, msg=None)
+ .. method:: assertIn(member, container, msg=None)
+ assertNotIn(member, container, msg=None)
- Test that *first* is (or is not) in *second*.
+ Test that *member* is (or is not) in *container*.
.. versionadded:: 3.1
diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst
index 93efcef1..c92abe73 100644
--- a/Doc/library/weakref.rst
+++ b/Doc/library/weakref.rst
@@ -159,13 +159,6 @@ Extension types can easily be made to support weak references; see
application without adding attributes to those objects. This can be especially
useful with objects that override attribute accesses.
- .. note::
-
- Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
- dictionary, it must not change size when iterating over it. This can be
- difficult to ensure for a :class:`WeakKeyDictionary` because actions
- performed by the program during iteration may cause items in the
- dictionary to vanish "by magic" (as a side effect of garbage collection).
:class:`WeakKeyDictionary` objects have an additional method that
exposes the internal references directly. The references are not guaranteed to
@@ -185,13 +178,6 @@ than needed.
Mapping class that references values weakly. Entries in the dictionary will be
discarded when no strong reference to the value exists any more.
- .. note::
-
- Caution: Because a :class:`WeakValueDictionary` is built on top of a Python
- dictionary, it must not change size when iterating over it. This can be
- difficult to ensure for a :class:`WeakValueDictionary` because actions performed
- by the program during iteration may cause items in the dictionary to vanish "by
- magic" (as a side effect of garbage collection).
:class:`WeakValueDictionary` objects have an additional method that has the
same issues as the :meth:`keyrefs` method of :class:`WeakKeyDictionary`
diff --git a/Doc/library/zipapp.rst b/Doc/library/zipapp.rst
index 72831525..fb40a2b3 100644
--- a/Doc/library/zipapp.rst
+++ b/Doc/library/zipapp.rst
@@ -198,7 +198,7 @@ Pack up a directory into an archive, and run it.
The same can be done using the :func:`create_archive` function::
>>> import zipapp
- >>> zipapp.create_archive('myapp.pyz', 'myapp')
+ >>> zipapp.create_archive('myapp', 'myapp.pyz')
To make the application directly executable on POSIX, specify an interpreter
to use.
diff --git a/Doc/make.bat b/Doc/make.bat
index d8085042..b92a4bd4 100644
--- a/Doc/make.bat
+++ b/Doc/make.bat
@@ -13,7 +13,7 @@ if not defined SPHINXBUILD (
%PYTHON% -c "import sphinx" > nul 2> nul
if errorlevel 1 (
echo Installing sphinx with %PYTHON%
- %PYTHON% -m pip install sphinx
+ %PYTHON% -m pip install sphinx==2.2.0
if errorlevel 1 exit /B
)
set SPHINXBUILD=%PYTHON% -c "import sphinx.cmd.build, sys; sys.exit(sphinx.cmd.build.main())"
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
index 1212dc61..af28c171 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -17,7 +17,7 @@ Objects, values and types
:dfn:`Objects` are Python's abstraction for data. All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
-conformance to Von Neumann's model of a "stored program computer," code is also
+conformance to Von Neumann's model of a "stored program computer", code is also
represented by objects.)
.. index::
@@ -420,6 +420,11 @@ Mappings
equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index
the same dictionary entry.
+ Dictionaries preserve insertion order, meaning that keys will be produced
+ in the same order they were added sequentially over the dictionary.
+ Replacing an existing key does not change the order, however removing a key
+ and re-inserting it will add it to the end instead of keeping its old place.
+
Dictionaries are mutable; they can be created by the ``{...}`` notation (see
section :ref:`dict`).
@@ -431,6 +436,11 @@ Mappings
additional examples of mapping types, as does the :mod:`collections`
module.
+ .. versionchanged:: 3.7
+ Dictionaries did not preserve insertion order in versions of Python before 3.6.
+ In CPython 3.6, insertion order was preserved, but it was considered
+ an implementation detail at that time rather than a language guarantee.
+
Callable types
.. index::
object: callable
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index 0a61ded2..3c14fc98 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -28,7 +28,7 @@ Arithmetic conversions
.. index:: pair: arithmetic; conversion
When a description of an arithmetic operator below uses the phrase "the numeric
-arguments are converted to a common type," this means that the operator
+arguments are converted to a common type", this means that the operator
implementation for built-in types works as follows:
* If either argument is a complex number, the other is converted to complex;
@@ -1420,8 +1420,9 @@ built-in types.
The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
special. Any ordered comparison of a number to a not-a-number value is false.
A counter-intuitive implication is that not-a-number values are not equal to
- themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3``, ``x
- == x``, ``x != x`` are all false. This behavior is compliant with IEEE 754.
+ themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and
+ ``x == x`` are all false, while ``x != x`` is true. This behavior is
+ compliant with IEEE 754.
* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be
compared within and across their types. They compare lexicographically using
diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst
index 9f51f41e..b6eaacb4 100644
--- a/Doc/reference/lexical_analysis.rst
+++ b/Doc/reference/lexical_analysis.rst
@@ -325,7 +325,7 @@ of identifiers is based on NFKC.
A non-normative HTML file listing all valid identifier characters for Unicode
4.1 can be found at
-https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html.
+https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt
.. _keywords:
@@ -376,11 +376,11 @@ characters:
information on this convention.
``__*__``
- System-defined names. These names are defined by the interpreter and its
- implementation (including the standard library). Current system names are
- discussed in the :ref:`specialnames` section and elsewhere. More will likely
- be defined in future versions of Python. *Any* use of ``__*__`` names, in
- any context, that does not follow explicitly documented use, is subject to
+ System-defined names, informally known as "dunder" names. These names are
+ defined by the interpreter and its implementation (including the standard library).
+ Current system names are discussed in the :ref:`specialnames` section and elsewhere.
+ More will likely be defined in future versions of Python. *Any* use of ``__*__`` names,
+ in any context, that does not follow explicitly documented use, is subject to
breakage without warning.
``__*``
diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py
index 466e84c2..3b6fa900 100644
--- a/Doc/tools/extensions/pyspecific.py
+++ b/Doc/tools/extensions/pyspecific.py
@@ -236,7 +236,8 @@ class DeprecatedRemoved(Directive):
final_argument_whitespace = True
option_spec = {}
- _label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
+ _deprecated_label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
+ _removed_label = 'Deprecated since version {deprecated}, removed in version {removed}'
def run(self):
node = addnodes.versionmodified()
@@ -244,7 +245,15 @@ class DeprecatedRemoved(Directive):
node['type'] = 'deprecated-removed'
version = (self.arguments[0], self.arguments[1])
node['version'] = version
- label = translators['sphinx'].gettext(self._label)
+ env = self.state.document.settings.env
+ current_version = tuple(int(e) for e in env.config.version.split('.'))
+ removed_version = tuple(int(e) for e in self.arguments[1].split('.'))
+ if current_version < removed_version:
+ label = self._deprecated_label
+ else:
+ label = self._removed_label
+
+ label = translators['sphinx'].gettext(label)
text = label.format(deprecated=self.arguments[0], removed=self.arguments[1])
if len(self.arguments) == 3:
inodes, messages = self.state.inline_text(self.arguments[2],
diff --git a/Doc/tools/static/switchers.js b/Doc/tools/static/switchers.js
index e1ef91a8..c51f178c 100644
--- a/Doc/tools/static/switchers.js
+++ b/Doc/tools/static/switchers.js
@@ -10,7 +10,8 @@
'(?:release/\\d.\\d[\\x\\d\\.]*)'];
var all_versions = {
- '3.9': 'dev (3.9)',
+ '3.10': 'dev (3.10)',
+ '3.9': 'pre (3.9)',
'3.8': '3.8',
'3.7': '3.7',
'3.6': '3.6',
diff --git a/Doc/tools/templates/download.html b/Doc/tools/templates/download.html
index d9364d6c..987c63a7 100644
--- a/Doc/tools/templates/download.html
+++ b/Doc/tools/templates/download.html
@@ -40,7 +40,7 @@ Python in one of various formats, follow one of links in this table.
These archives contain all the content in the documentation.
-
HTML Help (.chm) files are made available in the "Windows" section
+
HTML Help (.chm) files are made available in the "Windows" section
on the Python
download page.
diff --git a/Doc/tools/templates/dummy.html b/Doc/tools/templates/dummy.html
index 8d94137b..68ae3ad1 100644
--- a/Doc/tools/templates/dummy.html
+++ b/Doc/tools/templates/dummy.html
@@ -5,3 +5,4 @@ In extensions/pyspecific.py:
{% trans %}CPython implementation detail:{% endtrans %}
{% trans %}Deprecated since version {deprecated}, will be removed in version {removed}{% endtrans %}
+{% trans %}Deprecated since version {deprecated}, removed in version {removed}{% endtrans %}
diff --git a/Doc/tools/templates/indexsidebar.html b/Doc/tools/templates/indexsidebar.html
index 36f94ee0..c5924fd5 100644
--- a/Doc/tools/templates/indexsidebar.html
+++ b/Doc/tools/templates/indexsidebar.html
@@ -2,7 +2,8 @@
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index 5160145f..26c4461b 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -323,7 +323,7 @@ Instance Objects
Now what can we do with instance objects? The only operations understood by
instance objects are attribute references. There are two kinds of valid
-attribute names, data attributes and methods.
+attribute names: data attributes and methods.
*data attributes* correspond to "instance variables" in Smalltalk, and to "data
members" in C++. Data attributes need not be declared; like local variables,
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index 74f381d4..62a982c1 100644
--- a/Doc/tutorial/inputoutput.rst
+++ b/Doc/tutorial/inputoutput.rst
@@ -172,7 +172,7 @@ Positional and keyword arguments can be arbitrarily combined::
If you have a really long format string that you don't want to split up, it
would be nice if you could reference the variables to be formatted by name
instead of by position. This can be done by simply passing the dict and using
-square brackets ``'[]'`` to access the keys ::
+square brackets ``'[]'`` to access the keys. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
@@ -257,10 +257,10 @@ left with zeros. It understands about plus and minus signs::
Old string formatting
---------------------
-The ``%`` operator can also be used for string formatting. It interprets the
-left argument much like a :c:func:`sprintf`\ -style format string to be applied
-to the right argument, and returns the string resulting from this formatting
-operation. For example::
+The % operator (modulo) can also be used for string formatting. Given ``'string'
+% values``, instances of ``%`` in ``string`` are replaced with zero or more
+elements of ``values``. This operation is commonly known as string
+interpolation. For example::
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
diff --git a/Doc/using/mac.rst b/Doc/using/mac.rst
index e685993b..ef5817d3 100644
--- a/Doc/using/mac.rst
+++ b/Doc/using/mac.rst
@@ -27,9 +27,8 @@ What you get after installing is a number of things:
* A :file:`Python 3.7` folder in your :file:`Applications` folder. In here
you find IDLE, the development environment that is a standard part of official
- Python distributions; PythonLauncher, which handles double-clicking Python
- scripts from the Finder; and the "Build Applet" tool, which allows you to
- package Python scripts as standalone applications on your system.
+ Python distributions; and PythonLauncher, which handles double-clicking Python
+ scripts from the Finder.
* A framework :file:`/Library/Frameworks/Python.framework`, which includes the
Python executable and libraries. The installer adds this location to your shell
@@ -159,11 +158,6 @@ https://riverbankcomputing.com/software/pyqt/intro.
Distributing Python Applications on the Mac
===========================================
-The "Build Applet" tool that is placed in the MacPython 3.6 folder is fine for
-packaging small Python scripts on your own machine to run as a standard Mac
-application. This tool, however, is not robust enough to distribute Python
-applications to other users.
-
The standard tool for deploying standalone Python applications on the Mac is
:program:`py2app`. More information on installing and using py2app can be found
at http://undefined.org/python/#py2app.
diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst
index f5dddb5a..819d3e83 100644
--- a/Doc/using/windows.rst
+++ b/Doc/using/windows.rst
@@ -108,9 +108,7 @@ approximately 32,000 characters. Your administrator will need to activate the
to ``1``.
This allows the :func:`open` function, the :mod:`os` module and most other
-path functionality to accept and return paths longer than 260 characters when
-using strings. (Use of bytes as paths is deprecated on Windows, and this feature
-is not available when using bytes.)
+path functionality to accept and return paths longer than 260 characters.
After changing the above option, no further configuration is required.
diff --git a/Include/object.h b/Include/object.h
index bcf78afe..e212fca1 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -26,7 +26,7 @@ of data it contains. An object's type is fixed when it is created.
Types themselves are represented as objects; an object contains a
pointer to the corresponding type object. The type itself has a type
pointer pointing to the object representing the type 'type', which
-contains a pointer to itself!).
+contains a pointer to itself!.
Objects do not float around in memory; once allocated an object keeps
the same size and address. Objects that must hold variable-size data
diff --git a/Include/patchlevel.h b/Include/patchlevel.h
index dbe6b108..c1bdb834 100644
--- a/Include/patchlevel.h
+++ b/Include/patchlevel.h
@@ -18,12 +18,12 @@
/*--start constants--*/
#define PY_MAJOR_VERSION 3
#define PY_MINOR_VERSION 7
-#define PY_MICRO_VERSION 7
+#define PY_MICRO_VERSION 8
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
#define PY_RELEASE_SERIAL 0
/* Version as a string */
-#define PY_VERSION "3.7.7"
+#define PY_VERSION "3.7.8"
/*--end constants--*/
/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
diff --git a/Include/pystate.h b/Include/pystate.h
index f16ffb8f..819c1427 100644
--- a/Include/pystate.h
+++ b/Include/pystate.h
@@ -216,6 +216,7 @@ typedef struct _ts {
struct _ts *next;
PyInterpreterState *interp;
+ /* Borrowed reference to the current frame (it can be NULL) */
struct _frame *frame;
int recursion_depth;
char overflowed; /* The stack has overflowed. Allow 50 more calls
diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py
index db6674ea..e9efce7d 100644
--- a/Lib/_osx_support.py
+++ b/Lib/_osx_support.py
@@ -211,7 +211,7 @@ def _remove_universal_flags(_config_vars):
if cv in _config_vars and cv not in os.environ:
flags = _config_vars[cv]
flags = re.sub(r'-arch\s+\w+\s', ' ', flags, flags=re.ASCII)
- flags = re.sub('-isysroot [^ \t]*', ' ', flags)
+ flags = re.sub(r'-isysroot\s*\S+', ' ', flags)
_save_modified_value(_config_vars, cv, flags)
return _config_vars
@@ -287,7 +287,7 @@ def _check_for_unavailable_sdk(_config_vars):
# to /usr and /System/Library by either a standalone CLT
# package or the CLT component within Xcode.
cflags = _config_vars.get('CFLAGS', '')
- m = re.search(r'-isysroot\s+(\S+)', cflags)
+ m = re.search(r'-isysroot\s*(\S+)', cflags)
if m is not None:
sdk = m.group(1)
if not os.path.exists(sdk):
@@ -295,7 +295,7 @@ def _check_for_unavailable_sdk(_config_vars):
# Do not alter a config var explicitly overridden by env var
if cv in _config_vars and cv not in os.environ:
flags = _config_vars[cv]
- flags = re.sub(r'-isysroot\s+\S+(?:\s|$)', ' ', flags)
+ flags = re.sub(r'-isysroot\s*\S+(?:\s|$)', ' ', flags)
_save_modified_value(_config_vars, cv, flags)
return _config_vars
@@ -320,7 +320,7 @@ def compiler_fixup(compiler_so, cc_args):
stripArch = stripSysroot = True
else:
stripArch = '-arch' in cc_args
- stripSysroot = '-isysroot' in cc_args
+ stripSysroot = any(arg for arg in cc_args if arg.startswith('-isysroot'))
if stripArch or 'ARCHFLAGS' in os.environ:
while True:
@@ -338,23 +338,34 @@ def compiler_fixup(compiler_so, cc_args):
if stripSysroot:
while True:
- try:
- index = compiler_so.index('-isysroot')
+ indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
+ if not indices:
+ break
+ index = indices[0]
+ if compiler_so[index] == '-isysroot':
# Strip this argument and the next one:
del compiler_so[index:index+2]
- except ValueError:
- break
+ else:
+ # It's '-isysroot/some/path' in one arg
+ del compiler_so[index:index+1]
# Check if the SDK that is used during compilation actually exists,
# the universal build requires the usage of a universal SDK and not all
# users have that installed by default.
sysroot = None
- if '-isysroot' in cc_args:
- idx = cc_args.index('-isysroot')
- sysroot = cc_args[idx+1]
- elif '-isysroot' in compiler_so:
- idx = compiler_so.index('-isysroot')
- sysroot = compiler_so[idx+1]
+ argvar = cc_args
+ indices = [i for i,x in enumerate(cc_args) if x.startswith('-isysroot')]
+ if not indices:
+ argvar = compiler_so
+ indices = [i for i,x in enumerate(compiler_so) if x.startswith('-isysroot')]
+
+ for idx in indices:
+ if argvar[idx] == '-isysroot':
+ sysroot = argvar[idx+1]
+ break
+ else:
+ sysroot = argvar[idx][len('-isysroot'):]
+ break
if sysroot and not os.path.isdir(sysroot):
from distutils import log
diff --git a/Lib/ast.py b/Lib/ast.py
index 1bc6b38d..818d5638 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -298,11 +298,11 @@ class NodeTransformer(NodeVisitor):
class RewriteName(NodeTransformer):
def visit_Name(self, node):
- return copy_location(Subscript(
+ return Subscript(
value=Name(id='data', ctx=Load()),
slice=Index(value=Str(s=node.id)),
ctx=node.ctx
- ), node)
+ )
Keep in mind that if the node you're operating on has child nodes you must
either transform the child nodes yourself or call the :meth:`generic_visit`
diff --git a/Lib/asyncio/unix_events.py b/Lib/asyncio/unix_events.py
index 7034fc28..e037e129 100644
--- a/Lib/asyncio/unix_events.py
+++ b/Lib/asyncio/unix_events.py
@@ -98,7 +98,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
try:
# Register a dummy signal handler to ask Python to write the signal
- # number in the wakup file descriptor. _process_self_data() will
+ # number in the wakeup file descriptor. _process_self_data() will
# read signal numbers from this file descriptor to handle signals.
signal.signal(sig, _sighandler_noop)
diff --git a/Lib/cgi.py b/Lib/cgi.py
index df84f1fe..5a001667 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -217,7 +217,10 @@ def parse_multipart(fp, pdict, encoding="utf-8", errors="replace"):
ctype = "multipart/form-data; boundary={}".format(boundary)
headers = Message()
headers.set_type(ctype)
- headers['Content-Length'] = pdict['CONTENT-LENGTH']
+ try:
+ headers['Content-Length'] = pdict['CONTENT-LENGTH']
+ except KeyError:
+ pass
fs = FieldStorage(fp, headers=headers, encoding=encoding, errors=errors,
environ={'REQUEST_METHOD': 'POST'})
return {k: fs.getlist(k) for k in fs}
@@ -753,7 +756,8 @@ class FieldStorage:
last_line_lfend = True
_read = 0
while 1:
- if self.limit is not None and _read >= self.limit:
+
+ if self.limit is not None and 0 <= self.limit <= _read:
break
line = self.fp.readline(1<<16) # bytes
self.bytes_read += len(line)
diff --git a/Lib/codeop.py b/Lib/codeop.py
index 0fa677f6..3c2bb608 100644
--- a/Lib/codeop.py
+++ b/Lib/codeop.py
@@ -57,6 +57,7 @@ Compile():
"""
import __future__
+import warnings
_features = [getattr(__future__, fname)
for fname in __future__.all_feature_names]
@@ -83,15 +84,18 @@ def _maybe_compile(compiler, source, filename, symbol):
except SyntaxError as err:
pass
- try:
- code1 = compiler(source + "\n", filename, symbol)
- except SyntaxError as e:
- err1 = e
+ # Suppress warnings after the first compile to avoid duplication.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ try:
+ code1 = compiler(source + "\n", filename, symbol)
+ except SyntaxError as e:
+ err1 = e
- try:
- code2 = compiler(source + "\n\n", filename, symbol)
- except SyntaxError as e:
- err2 = e
+ try:
+ code2 = compiler(source + "\n\n", filename, symbol)
+ except SyntaxError as e:
+ err2 = e
try:
if code:
@@ -112,7 +116,8 @@ def compile_command(source, filename="", symbol="single"):
source -- the source string; may contain \n characters
filename -- optional filename from which source was read; default
""
- symbol -- optional grammar start symbol; "single" (default) or "eval"
+ symbol -- optional grammar start symbol; "single" (default), "exec"
+ or "eval"
Return value / exceptions raised:
diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py
index f622093d..937a06d9 100644
--- a/Lib/ctypes/test/test_callbacks.py
+++ b/Lib/ctypes/test/test_callbacks.py
@@ -287,6 +287,21 @@ class SampleCallbacksTestCase(unittest.TestCase):
self.assertEqual(s.second, check.second)
self.assertEqual(s.third, check.third)
+ def test_callback_too_many_args(self):
+ def func(*args):
+ return len(args)
+
+ CTYPES_MAX_ARGCOUNT = 1024
+ proto = CFUNCTYPE(c_int, *(c_int,) * CTYPES_MAX_ARGCOUNT)
+ cb = proto(func)
+ args1 = (1,) * CTYPES_MAX_ARGCOUNT
+ self.assertEqual(cb(*args1), CTYPES_MAX_ARGCOUNT)
+
+ args2 = (1,) * (CTYPES_MAX_ARGCOUNT + 1)
+ with self.assertRaises(ArgumentError):
+ cb(*args2)
+
+
################################################################
if __name__ == '__main__':
diff --git a/Lib/distutils/tests/__init__.py b/Lib/distutils/tests/__init__.py
index 1b939cbd..5d2e69e3 100644
--- a/Lib/distutils/tests/__init__.py
+++ b/Lib/distutils/tests/__init__.py
@@ -15,6 +15,7 @@ by import rather than matching pre-defined names.
import os
import sys
import unittest
+import warnings
from test.support import run_unittest
@@ -22,6 +23,7 @@ here = os.path.dirname(__file__) or os.curdir
def test_suite():
+ old_filters = warnings.filters[:]
suite = unittest.TestSuite()
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
@@ -29,6 +31,10 @@ def test_suite():
__import__(modname)
module = sys.modules[modname]
suite.addTest(module.test_suite())
+ # bpo-40055: Save/restore warnings filters to leave them unchanged.
+ # Importing tests imports docutils which imports pkg_resources which adds a
+ # warnings filter.
+ warnings.filters[:] = old_filters
return suite
diff --git a/Lib/distutils/unixccompiler.py b/Lib/distutils/unixccompiler.py
index d10a78da..4d7a6de7 100644
--- a/Lib/distutils/unixccompiler.py
+++ b/Lib/distutils/unixccompiler.py
@@ -288,7 +288,7 @@ class UnixCCompiler(CCompiler):
# vs
# /usr/lib/libedit.dylib
cflags = sysconfig.get_config_var('CFLAGS')
- m = re.search(r'-isysroot\s+(\S+)', cflags)
+ m = re.search(r'-isysroot\s*(\S+)', cflags)
if m is None:
sysroot = '/'
else:
diff --git a/Lib/doctest.py b/Lib/doctest.py
index 2a4b8c7d..47917b48 100644
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -211,6 +211,13 @@ def _normalize_module(module, depth=2):
else:
raise TypeError("Expected a module, string, or None")
+def _newline_convert(data):
+ # We have two cases to cover and we need to make sure we do
+ # them in the right order
+ for newline in ('\r\n', '\r'):
+ data = data.replace(newline, '\n')
+ return data
+
def _load_testfile(filename, package, module_relative, encoding):
if module_relative:
package = _normalize_module(package, 3)
@@ -221,7 +228,7 @@ def _load_testfile(filename, package, module_relative, encoding):
file_contents = file_contents.decode(encoding)
# get_data() opens files as 'rb', so one must do the equivalent
# conversion as universal newlines would do.
- return file_contents.replace(os.linesep, '\n'), filename
+ return _newline_convert(file_contents), filename
with open(filename, encoding=encoding) as f:
return f.read(), filename
diff --git a/Lib/email/_header_value_parser.py b/Lib/email/_header_value_parser.py
index 3197d497..b7c30c47 100644
--- a/Lib/email/_header_value_parser.py
+++ b/Lib/email/_header_value_parser.py
@@ -1211,12 +1211,21 @@ def get_bare_quoted_string(value):
if value[0] in WSP:
token, value = get_fws(value)
elif value[:2] == '=?':
+ valid_ew = False
try:
token, value = get_encoded_word(value)
bare_quoted_string.defects.append(errors.InvalidHeaderDefect(
"encoded word inside quoted string"))
+ valid_ew = True
except errors.HeaderParseError:
token, value = get_qcontent(value)
+ # Collapse the whitespace between two encoded words that occur in a
+ # bare-quoted-string.
+ if valid_ew and len(bare_quoted_string) > 1:
+ if (bare_quoted_string[-1].token_type == 'fws' and
+ bare_quoted_string[-2].token_type == 'encoded-word'):
+ bare_quoted_string[-1] = EWWhiteSpaceTerminal(
+ bare_quoted_string[-1], 'fws')
else:
token, value = get_qcontent(value)
bare_quoted_string.append(token)
diff --git a/Lib/email/headerregistry.py b/Lib/email/headerregistry.py
index 0218cbfb..fe30fc2c 100644
--- a/Lib/email/headerregistry.py
+++ b/Lib/email/headerregistry.py
@@ -31,6 +31,11 @@ class Address:
without any Content Transfer Encoding.
"""
+
+ inputs = ''.join(filter(None, (display_name, username, domain, addr_spec)))
+ if '\r' in inputs or '\n' in inputs:
+ raise ValueError("invalid arguments; address parts cannot contain CR or LF")
+
# This clause with its potential 'raise' may only happen when an
# application program creates an Address object using an addr_spec
# keyword. The email library code itself must always supply username
diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py
index 7a0d3ee0..94d40b0c 100644
--- a/Lib/ensurepip/__init__.py
+++ b/Lib/ensurepip/__init__.py
@@ -2,19 +2,20 @@ import os
import os.path
import pkgutil
import sys
+import runpy
import tempfile
__all__ = ["version", "bootstrap"]
-_SETUPTOOLS_VERSION = "41.2.0"
+_SETUPTOOLS_VERSION = "47.1.0"
-_PIP_VERSION = "19.2.3"
+_PIP_VERSION = "20.1.1"
_PROJECTS = [
- ("setuptools", _SETUPTOOLS_VERSION),
- ("pip", _PIP_VERSION),
+ ("setuptools", _SETUPTOOLS_VERSION, "py3"),
+ ("pip", _PIP_VERSION, "py2.py3"),
]
@@ -23,9 +24,18 @@ def _run_pip(args, additional_paths=None):
if additional_paths is not None:
sys.path = additional_paths + sys.path
- # Install the bundled software
- import pip._internal
- return pip._internal.main(args)
+ # Invoke pip as if it's the main module, and catch the exit.
+ backup_argv = sys.argv[:]
+ sys.argv[1:] = args
+ try:
+ # run_module() alters sys.modules and sys.argv, but restores them at exit
+ runpy.run_module("pip", run_name="__main__", alter_sys=True)
+ except SystemExit as exc:
+ return exc.code
+ finally:
+ sys.argv[:] = backup_argv
+
+ raise SystemError("pip did not exit, this should never happen")
def version():
@@ -92,8 +102,8 @@ def _bootstrap(*, root=None, upgrade=False, user=False,
# Put our bundled wheels into a temporary directory and construct the
# additional paths that need added to sys.path
additional_paths = []
- for project, version in _PROJECTS:
- wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version)
+ for project, version, py_tag in _PROJECTS:
+ wheel_name = "{}-{}-{}-none-any.whl".format(project, version, py_tag)
whl = pkgutil.get_data(
"ensurepip",
"_bundled/{}".format(wheel_name),
@@ -104,7 +114,7 @@ def _bootstrap(*, root=None, upgrade=False, user=False,
additional_paths.append(os.path.join(tmpdir, wheel_name))
# Construct the arguments to be passed to the pip command
- args = ["install", "--no-index", "--find-links", tmpdir]
+ args = ["install", "--no-cache-dir", "--no-index", "--find-links", tmpdir]
if root:
args += ["--root", root]
if upgrade:
diff --git a/Lib/ensurepip/_bundled/pip-19.2.3-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-19.2.3-py2.py3-none-any.whl
deleted file mode 100644
index 8118df8a..00000000
Binary files a/Lib/ensurepip/_bundled/pip-19.2.3-py2.py3-none-any.whl and /dev/null differ
diff --git a/Lib/ensurepip/_bundled/pip-20.1.1-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-20.1.1-py2.py3-none-any.whl
new file mode 100644
index 00000000..ea1d0f7c
Binary files /dev/null and b/Lib/ensurepip/_bundled/pip-20.1.1-py2.py3-none-any.whl differ
diff --git a/Lib/ensurepip/_bundled/setuptools-41.2.0-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/setuptools-41.2.0-py2.py3-none-any.whl
deleted file mode 100644
index 82df6f63..00000000
Binary files a/Lib/ensurepip/_bundled/setuptools-41.2.0-py2.py3-none-any.whl and /dev/null differ
diff --git a/Lib/ensurepip/_bundled/setuptools-47.1.0-py3-none-any.whl b/Lib/ensurepip/_bundled/setuptools-47.1.0-py3-none-any.whl
new file mode 100644
index 00000000..f87867ff
Binary files /dev/null and b/Lib/ensurepip/_bundled/setuptools-47.1.0-py3-none-any.whl differ
diff --git a/Lib/enum.py b/Lib/enum.py
index d0b03b4a..83e64101 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -66,6 +66,7 @@ class _EnumDict(dict):
self._member_names = []
self._last_values = []
self._ignore = []
+ self._auto_called = False
def __setitem__(self, key, value):
"""Changes anything not dundered or not a descriptor.
@@ -83,6 +84,9 @@ class _EnumDict(dict):
):
raise ValueError('_names_ are reserved for future Enum use')
if key == '_generate_next_value_':
+ # check if members already defined as auto()
+ if self._auto_called:
+ raise TypeError("_generate_next_value_ must be defined before members")
setattr(self, '_generate_next_value', value)
elif key == '_ignore_':
if isinstance(value, str):
@@ -106,6 +110,7 @@ class _EnumDict(dict):
# enum overwriting a descriptor?
raise TypeError('%r already defined as: %r' % (key, self[key]))
if isinstance(value, auto):
+ self._auto_called = True
if value.value == _auto_null:
value.value = self._generate_next_value(key, 1, len(self._member_names), self._last_values[:])
value = value.value
diff --git a/Lib/http/client.py b/Lib/http/client.py
index f7a183c7..09c57af8 100644
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -850,6 +850,8 @@ class HTTPConnection:
(self.host, self.port) = self._get_hostport(host, port)
+ self._validate_host(self.host)
+
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_connection = socket.create_connection
@@ -1205,6 +1207,14 @@ class HTTPConnection:
raise InvalidURL(f"URL can't contain control characters. {url!r} "
f"(found at least {match.group()!r})")
+ def _validate_host(self, host):
+ """Validate a host so it doesn't contain control characters."""
+ # Prevent CVE-2019-18348.
+ match = _contains_disallowed_url_pchar_re.search(host)
+ if match:
+ raise InvalidURL(f"URL can't contain control characters. {host!r} "
+ f"(found at least {match.group()!r})")
+
def putheader(self, header, *values):
"""Send a request header line to the server.
diff --git a/Lib/idlelib/Icons/README.txt b/Lib/idlelib/Icons/README.txt
new file mode 100644
index 00000000..8b471629
--- /dev/null
+++ b/Lib/idlelib/Icons/README.txt
@@ -0,0 +1,9 @@
+The IDLE icons are from https://bugs.python.org/issue1490384
+
+Created by Andrew Clover.
+
+The original sources are available from Andrew's website:
+https://www.doxdesk.com/software/py/pyicons.html
+
+Various different formats and sizes are available at this GitHub Pull Request:
+https://github.com/python/cpython/pull/17473
diff --git a/Lib/idlelib/Icons/idle.icns b/Lib/idlelib/Icons/idle.icns
deleted file mode 100644
index f65e3130..00000000
Binary files a/Lib/idlelib/Icons/idle.icns and /dev/null differ
diff --git a/Lib/idlelib/Icons/idle_256.png b/Lib/idlelib/Icons/idle_256.png
new file mode 100644
index 00000000..99ffa6fa
Binary files /dev/null and b/Lib/idlelib/Icons/idle_256.png differ
diff --git a/Lib/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt
index 0fa08962..c751dc3b 100644
--- a/Lib/idlelib/NEWS.txt
+++ b/Lib/idlelib/NEWS.txt
@@ -1,7 +1,28 @@
-What's New in IDLE 3.7.6
-Released on 2019-12-16?
+What's New in IDLE 3.7.8
+Released on 2020-06-27?
+======================================
+
+
+bpo-40723: Make test_idle pass when run after import.
+Patch by Florian Dahlitz.
+
+bpo-38689: IDLE will no longer freeze when inspect.signature fails
+when fetching a calltip.
+
+
+What's New in IDLE 3.7.7
+Released on 2020-03-10
======================================
+bpo-27115: For 'Go to Line', use a Query entry box subclass with
+IDLE standard behavior and improved error checking.
+
+bpo-39885: When a context menu is invoked by right-clicking outside
+of a selection, clear the selection and move the cursor. Cut and
+Copy require that the click be within the selection.
+
+bpo-39852: Edit "Go to line" now clears any selection, preventing
+accidental deletion. It also updates Ln and Col on the status bar.
bpo-39781: Selecting code context lines no longer causes a jump.
@@ -23,6 +44,11 @@ bpo-32989: Add tests for editor newline_and_indent_event method.
Remove unneeded arguments and dead code from pyparse
find_good_parse_start method.
+
+What's New in IDLE 3.7.6
+Released on 2019-12-18
+======================================
+
bpo-38943: Fix autocomplete windows not always appearing on some
systems. Patch by Johnny Najera.
diff --git a/Lib/idlelib/autocomplete_w.py b/Lib/idlelib/autocomplete_w.py
index 0643c092..fe7a6be8 100644
--- a/Lib/idlelib/autocomplete_w.py
+++ b/Lib/idlelib/autocomplete_w.py
@@ -4,7 +4,7 @@ An auto-completion window for IDLE, used by the autocomplete extension
import platform
from tkinter import *
-from tkinter.ttk import Frame, Scrollbar
+from tkinter.ttk import Scrollbar
from idlelib.autocomplete import FILES, ATTRS
from idlelib.multicall import MC_SHIFT
diff --git a/Lib/idlelib/calltip.py b/Lib/idlelib/calltip.py
index 2e0db60d..d4092c78 100644
--- a/Lib/idlelib/calltip.py
+++ b/Lib/idlelib/calltip.py
@@ -129,20 +129,22 @@ def get_argspec(ob):
empty line or _MAX_LINES. For builtins, this typically includes
the arguments in addition to the return value.
'''
- argspec = default = ""
+ # Determine function object fob to inspect.
try:
ob_call = ob.__call__
- except BaseException:
- return default
-
+ except BaseException: # Buggy user object could raise anything.
+ return '' # No popup for non-callables.
fob = ob_call if isinstance(ob_call, types.MethodType) else ob
+ # Initialize argspec and wrap it to get lines.
try:
argspec = str(inspect.signature(fob))
- except ValueError as err:
+ except Exception as err:
msg = str(err)
if msg.startswith(_invalid_method):
return _invalid_method
+ else:
+ argspec = ''
if '/' in argspec and len(argspec) < _MAX_COLS - len(_argument_positional):
# Add explanation TODO remove after 3.7, before 3.9.
@@ -154,6 +156,7 @@ def get_argspec(ob):
lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT)
if len(argspec) > _MAX_COLS else [argspec] if argspec else [])
+ # Augment lines from docstring, if any, and join to get argspec.
if isinstance(ob_call, types.MethodType):
doc = ob_call.__doc__
else:
@@ -167,9 +170,8 @@ def get_argspec(ob):
line = line[: _MAX_COLS - 3] + '...'
lines.append(line)
argspec = '\n'.join(lines)
- if not argspec:
- argspec = _default_callable_argspec
- return argspec
+
+ return argspec or _default_callable_argspec
if __name__ == '__main__':
diff --git a/Lib/idlelib/config_key.py b/Lib/idlelib/config_key.py
index 4478323f..7510aa9f 100644
--- a/Lib/idlelib/config_key.py
+++ b/Lib/idlelib/config_key.py
@@ -1,7 +1,7 @@
"""
Dialog for building Tkinter accelerator key bindings
"""
-from tkinter import Toplevel, Listbox, Text, StringVar, TclError
+from tkinter import Toplevel, Listbox, StringVar, TclError
from tkinter.ttk import Frame, Button, Checkbutton, Entry, Label, Scrollbar
from tkinter import messagebox
import string
diff --git a/Lib/idlelib/configdialog.py b/Lib/idlelib/configdialog.py
index 9d5c2cde..82596498 100644
--- a/Lib/idlelib/configdialog.py
+++ b/Lib/idlelib/configdialog.py
@@ -11,7 +11,7 @@ Refer to comments in EditorWindow autoindent code for details.
"""
import re
-from tkinter import (Toplevel, Listbox, Text, Scale, Canvas,
+from tkinter import (Toplevel, Listbox, Scale, Canvas,
StringVar, BooleanVar, IntVar, TRUE, FALSE,
TOP, BOTTOM, RIGHT, LEFT, SOLID, GROOVE,
NONE, BOTH, X, Y, W, E, EW, NS, NSEW, NW,
diff --git a/Lib/idlelib/editor.py b/Lib/idlelib/editor.py
index 04c786dc..a178eaf9 100644
--- a/Lib/idlelib/editor.py
+++ b/Lib/idlelib/editor.py
@@ -499,14 +499,23 @@ class EditorWindow(object):
rmenu = None
def right_menu_event(self, event):
- self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
+ text = self.text
+ newdex = text.index(f'@{event.x},{event.y}')
+ try:
+ in_selection = (text.compare('sel.first', '<=', newdex) and
+ text.compare(newdex, '<=', 'sel.last'))
+ except TclError:
+ in_selection = False
+ if not in_selection:
+ text.tag_remove("sel", "1.0", "end")
+ text.mark_set("insert", newdex)
if not self.rmenu:
self.make_rmenu()
rmenu = self.rmenu
self.event = event
iswin = sys.platform[:3] == 'win'
if iswin:
- self.text.config(cursor="arrow")
+ text.config(cursor="arrow")
for item in self.rmenu_specs:
try:
@@ -519,7 +528,6 @@ class EditorWindow(object):
state = getattr(self, verify_state)()
rmenu.entryconfigure(label, state=state)
-
rmenu.tk_popup(event.x_root, event.y_root)
if iswin:
self.text.config(cursor="ibeam")
@@ -671,15 +679,16 @@ class EditorWindow(object):
def goto_line_event(self, event):
text = self.text
- lineno = tkSimpleDialog.askinteger("Goto",
- "Go to line number:",parent=text)
- if lineno is None:
- return "break"
- if lineno <= 0:
- text.bell()
- return "break"
- text.mark_set("insert", "%d.0" % lineno)
- text.see("insert")
+ lineno = query.Goto(
+ text, "Go To Line",
+ "Enter a positive integer\n"
+ "('big' = end of file):"
+ ).result
+ if lineno is not None:
+ text.tag_remove("sel", "1.0", "end")
+ text.mark_set("insert", f'{lineno}.0')
+ text.see("insert")
+ self.set_line_and_column()
return "break"
def open_module(self):
diff --git a/Lib/idlelib/help.html b/Lib/idlelib/help.html
index 0b2bdd2e..424c6b50 100644
--- a/Lib/idlelib/help.html
+++ b/Lib/idlelib/help.html
@@ -4,7 +4,7 @@
- IDLE — Python 3.9.0a1 documentation
+ IDLE — Python 3.9.0a4 documentation
@@ -17,7 +17,7 @@
@@ -71,7 +71,7 @@
Move cursor to the line number requested and make that line visible.
+
Go to Line
Move the cursor to the beginning of the line requested and make that
+line visible. A request past the end of the file goes to the end.
+Clear any selection and update the line and column status.
Show Completions
Open a scrollable list allowing selection of keywords and attributes. See
Completions in the Editing and navigation section below.
@@ -635,17 +637,20 @@ clash, or a single installation might need admin access. If one undo the
clash, or cannot or does not want to run as admin, it might be easiest to
completely remove Python and start over.
A zombie pythonw.exe process could be a problem. On Windows, use Task
-Manager to detect and stop one. Sometimes a restart initiated by a program
-crash or Keyboard Interrupt (control-C) may fail to connect. Dismissing
-the error box or Restart Shell on the Shell menu may fix a temporary problem.
+Manager to check for one and stop it if there is. Sometimes a restart
+initiated by a program crash or Keyboard Interrupt (control-C) may fail
+to connect. Dismissing the error box or using Restart Shell on the Shell
+menu may fix a temporary problem.
When IDLE first starts, it attempts to read user configuration files in
~/.idlerc/ (~ is oneâs home directory). If there is a problem, an error
message should be displayed. Leaving aside random disk glitches, this can
-be prevented by never editing the files by hand, using the configuration
-dialog, under Options, instead Options. Once it happens, the solution may
-be to delete one or more of the configuration files.
+be prevented by never editing the files by hand. Instead, use the
+configuration dialog, under Options. Once there is an error in a user
+configuration file, the best solution may be to delete it and start over
+with the settings dialog.
If IDLE quits with no message, and it was not started from a console, try
-starting from a console (python-midlelib) and see if a message appears.
+starting it from a console or terminal (python-midlelib) and see if
+this results in an error message.