From: DongHun Kwak
Date: Wed, 9 Dec 2020 00:35:23 +0000 (+0900)
Subject: Imported Upstream version 3.8.4
X-Git-Tag: upstream/3.8.4^0
X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=2aed1ddb5f6f43bf84d8f260bcea4d5dfb3f3157;p=platform%2Fupstream%2Fpython3.git
Imported Upstream version 3.8.4
---
diff --git a/Doc/Makefile b/Doc/Makefile
index 2169f1a3..b8ca1edf 100644
--- a/Doc/Makefile
+++ b/Doc/Makefile
@@ -143,7 +143,7 @@ clean:
venv:
$(PYTHON) -m venv $(VENVDIR)
$(VENVDIR)/bin/python3 -m pip install -U pip setuptools
- $(VENVDIR)/bin/python3 -m pip install -U Sphinx==1.8.2 blurb python-docs-theme
+ $(VENVDIR)/bin/python3 -m pip install -U Sphinx==2.3.1 blurb python-docs-theme
@echo "The venv has been created in the $(VENVDIR) directory"
dist:
diff --git a/Doc/c-api/init_config.rst b/Doc/c-api/init_config.rst
index 79a8815e..ff4ccb8d 100644
--- a/Doc/c-api/init_config.rst
+++ b/Doc/c-api/init_config.rst
@@ -196,12 +196,12 @@ PyPreConfig
Function to initialize a preconfiguration:
- .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
+ .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Initialize the preconfiguration with :ref:`Python Configuration
`.
- .. c:function:: void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
+ .. c:function:: void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Initialize the preconfiguration with :ref:`Isolated Configuration
`.
diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst
index f41d419b..3bada415 100644
--- a/Doc/c-api/long.rst
+++ b/Doc/c-api/long.rst
@@ -98,11 +98,9 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
.. c:function:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
- Convert a sequence of Unicode digits to a Python integer value. The Unicode
- string is first encoded to a byte string using :c:func:`PyUnicode_EncodeDecimal`
- and then converted using :c:func:`PyLong_FromString`.
+ Convert a sequence of Unicode digits to a Python integer value.
- .. deprecated-removed:: 3.3 4.0
+ .. deprecated-removed:: 3.3 3.10
Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
:c:func:`PyLong_FromUnicodeObject`.
@@ -110,9 +108,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
.. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base)
Convert a sequence of Unicode digits in the string *u* to a Python integer
- value. The Unicode string is first encoded to a byte string using
- :c:func:`PyUnicode_EncodeDecimal` and then converted using
- :c:func:`PyLong_FromString`.
+ value.
.. versionadded:: 3.3
diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst
index 2bf4a0f5..b261efe2 100644
--- a/Doc/c-api/unicode.rst
+++ b/Doc/c-api/unicode.rst
@@ -700,6 +700,8 @@ Extension modules can continue using them, as they will not be removed in Python
:c:func:`PyUnicode_AsWideChar`, :c:func:`PyUnicode_ReadChar` or similar new
APIs.
+ .. deprecated-removed:: 3.3 3.10
+
.. c:function:: PyObject* PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)
diff --git a/Doc/distributing/index.rst b/Doc/distributing/index.rst
index 5f7b3bbc..02379946 100644
--- a/Doc/distributing/index.rst
+++ b/Doc/distributing/index.rst
@@ -128,6 +128,7 @@ involved in creating and publishing a project:
* `Project structure`_
* `Building and packaging the project`_
* `Uploading the project to the Python Packaging Index`_
+* `The .pypirc file`_
.. _Project structure: \
https://packaging.python.org/tutorials/distributing-packages/
@@ -135,6 +136,8 @@ involved in creating and publishing a project:
https://packaging.python.org/tutorials/distributing-packages/#packaging-your-project
.. _Uploading the project to the Python Packaging Index: \
https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi
+.. _The .pypirc file: \
+ https://packaging.python.org/specifications/pypirc/
How do I...?
diff --git a/Doc/faq/general.rst b/Doc/faq/general.rst
index 3ef553e8..eee3c3c2 100644
--- a/Doc/faq/general.rst
+++ b/Doc/faq/general.rst
@@ -17,12 +17,13 @@ What is Python?
Python is an interpreted, interactive, object-oriented programming language. It
incorporates modules, exceptions, dynamic typing, very high level dynamic data
-types, and classes. Python combines remarkable power with very clear syntax.
-It has interfaces to many system calls and libraries, as well as to various
-window systems, and is extensible in C or C++. It is also usable as an
-extension language for applications that need a programmable interface.
-Finally, Python is portable: it runs on many Unix variants, on the Mac, and on
-Windows 2000 and later.
+types, and classes. It supports multiple programming paradigms beyond
+object-oriented programming, such as procedural and functional programming.
+Python combines remarkable power with very clear syntax. It has interfaces to
+many system calls and libraries, as well as to various window systems, and is
+extensible in C or C++. It is also usable as an extension language for
+applications that need a programmable interface. Finally, Python is portable:
+it runs on many Unix variants including Linux and macOS, and on Windows.
To find out more, start with :ref:`tutorial-index`. The `Beginner's Guide to
Python `_ links to other
@@ -295,8 +296,8 @@ How stable is Python?
---------------------
Very stable. New, stable releases have been coming out roughly every 6 to 18
-months since 1991, and this seems likely to continue. Currently there are
-usually around 18 months between major releases.
+months since 1991, and this seems likely to continue. As of version 3.9,
+Python will have a major new release every 12 months (:pep:`602`).
The developers issue "bugfix" releases of older versions, so the stability of
existing releases gradually improves. Bugfix releases, indicated by a third
@@ -314,8 +315,8 @@ be maintained after January 1, 2020 `
How many people are using Python?
---------------------------------
-There are probably tens of thousands of users, though it's difficult to obtain
-an exact count.
+There are probably millions of users, though it's difficult to obtain an exact
+count.
Python is available for free download, so there are no sales figures, and it's
available from many different sites and packaged with many Linux distributions,
diff --git a/Doc/glossary.rst b/Doc/glossary.rst
index 6189cb04..e997d366 100644
--- a/Doc/glossary.rst
+++ b/Doc/glossary.rst
@@ -189,6 +189,10 @@ Glossary
A list of bytecode instructions can be found in the documentation for
:ref:`the dis module `.
+ callback
+ A subroutine function which is passed as an argument to be executed at
+ some point in the future.
+
class
A template for creating user-defined objects. Class definitions
normally contain method definitions which operate on instances of the
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/library/asyncio-dev.rst b/Doc/library/asyncio-dev.rst
index 101e7817..0d302ea4 100644
--- a/Doc/library/asyncio-dev.rst
+++ b/Doc/library/asyncio-dev.rst
@@ -73,7 +73,7 @@ event loop, no other Tasks can run in the same thread. When a Task
executes an ``await`` expression, the running Task gets suspended, and
the event loop executes the next Task.
-To schedule a callback from a different OS thread, the
+To schedule a :term:`callback` from another OS thread, the
:meth:`loop.call_soon_threadsafe` method should be used. Example::
loop.call_soon_threadsafe(callback, *args)
diff --git a/Doc/library/asyncio-eventloop.rst b/Doc/library/asyncio-eventloop.rst
index 9022993e..32bc219c 100644
--- a/Doc/library/asyncio-eventloop.rst
+++ b/Doc/library/asyncio-eventloop.rst
@@ -179,8 +179,8 @@ Scheduling callbacks
.. method:: loop.call_soon(callback, *args, context=None)
- Schedule a *callback* to be called with *args* arguments at
- the next iteration of the event loop.
+ Schedule the *callback* :term:`callback` to be called with
+ *args* arguments at the next iteration of the event loop.
Callbacks are called in the order in which they are registered.
Each callback will be called exactly once.
diff --git a/Doc/library/asyncio-protocol.rst b/Doc/library/asyncio-protocol.rst
index ffac9018..816ddcd0 100644
--- a/Doc/library/asyncio-protocol.rst
+++ b/Doc/library/asyncio-protocol.rst
@@ -996,7 +996,7 @@ loop.subprocess_exec() and SubprocessProtocol
An example of a subprocess protocol used to get the output of a
subprocess and to wait for the subprocess exit.
-The subprocess is created by th :meth:`loop.subprocess_exec` method::
+The subprocess is created by the :meth:`loop.subprocess_exec` method::
import asyncio
import sys
diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst
index 1d87d2f8..eb1312a9 100644
--- a/Doc/library/asyncio-subprocess.rst
+++ b/Doc/library/asyncio-subprocess.rst
@@ -95,14 +95,14 @@ Creating Subprocesses
See the documentation of :meth:`loop.subprocess_shell` for other
parameters.
-.. important::
-
- It is the application's responsibility to ensure that all whitespace and
- special characters are quoted appropriately to avoid `shell injection
- `_
- vulnerabilities. The :func:`shlex.quote` function can be used to properly
- escape whitespace and special shell characters in strings that are going
- to be used to construct shell commands.
+ .. important::
+
+ It is the application's responsibility to ensure that all whitespace and
+ special characters are quoted appropriately to avoid `shell injection
+ `_
+ vulnerabilities. The :func:`shlex.quote` function can be used to properly
+ escape whitespace and special shell characters in strings that are going
+ to be used to construct shell commands.
.. deprecated-removed:: 3.8 3.10
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index 1a23661f..00ce5d4b 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -580,9 +580,9 @@ Waiting Primitives
.. function:: as_completed(aws, \*, loop=None, timeout=None)
Run :ref:`awaitable objects ` in the *aws*
- set concurrently. Return an iterator of :class:`Future` objects.
- Each Future object returned represents the earliest result
- from the set of the remaining awaitables.
+ set concurrently. Return an iterator of coroutines.
+ Each coroutine returned can be awaited to get the earliest next
+ result from the set of the remaining awaitables.
Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
all Futures are done.
@@ -592,8 +592,8 @@ Waiting Primitives
Example::
- for f in as_completed(aws):
- earliest_result = await f
+ for coro in as_completed(aws):
+ earliest_result = await coro
# ...
diff --git a/Doc/library/calendar.rst b/Doc/library/calendar.rst
index 56b75ef0..c3c04db8 100644
--- a/Doc/library/calendar.rst
+++ b/Doc/library/calendar.rst
@@ -349,7 +349,7 @@ For simple text calendars this module provides the following functions.
.. function:: monthcalendar(year, month)
Returns a matrix representing a month's calendar. Each row represents a week;
- days outside of the month a represented by zeros. Each week begins with Monday
+ days outside of the month are represented by zeros. Each week begins with Monday
unless set by :func:`setfirstweekday`.
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/collections.rst b/Doc/library/collections.rst
index 8dcf9451..d4297166 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -1150,6 +1150,8 @@ variants of :func:`functools.lru_cache`::
return value
def __setitem__(self, key, value):
+ if key in self:
+ self.move_to_end(key)
super().__setitem__(key, value)
if len(self) > self.maxsize:
oldest = next(iter(self))
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
index 61d39828..7a72c26d 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -167,6 +167,9 @@ The :mod:`csv` module defines the following classes:
All other optional or keyword arguments are passed to the underlying
:class:`reader` instance.
+ .. versionchanged:: 3.6
+ Returned rows are now of type :class:`OrderedDict`.
+
.. versionchanged:: 3.8
Returned rows are now of type :class:`dict`.
diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst
index 10edcac7..a7fbaaa1 100644
--- a/Doc/library/dataclasses.rst
+++ b/Doc/library/dataclasses.rst
@@ -23,7 +23,7 @@ using :pep:`526` type annotations. For example this code::
@dataclass
class InventoryItem:
- '''Class for keeping track of an item in inventory.'''
+ """Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 29c6b5a4..b733c440 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -35,7 +35,8 @@ on efficient attribute extraction for output formatting and manipulation.
Aware and Naive Objects
-----------------------
-Date and time objects may be categorized as "aware" or "naive."
+Date and time objects may be categorized as "aware" or "naive" depending on
+whether or not they include timezone information.
With sufficient knowledge of applicable algorithmic and political time
adjustments, such as time zone and daylight saving time information,
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/enum.rst b/Doc/library/enum.rst
index 75380847..2649b7d8 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 b1192e7b..75b6fa38 100644
--- a/Doc/library/idle.rst
+++ b/Doc/library/idle.rst
@@ -147,7 +147,7 @@ Go to Line
Clear any selection and update the line and column status.
Show Completions
- Open a scrollable list allowing selection of keywords and attributes. See
+ Open a scrollable list allowing selection of existing names. See
:ref:`Completions ` in the Editing and navigation section below.
Expand Word
@@ -469,52 +469,58 @@ are restricted to four spaces due to Tcl/Tk limitations.
See also the indent/dedent region commands on the
:ref:`Format menu `.
-
.. _completions:
Completions
^^^^^^^^^^^
-Completions are supplied for functions, classes, and attributes of classes,
-both built-in and user-defined. Completions are also provided for
-filenames.
-
-The AutoCompleteWindow (ACW) will open after a predefined delay (default is
-two seconds) after a '.' or (in a string) an os.sep is typed. If after one
-of those characters (plus zero or more other characters) a tab is typed
-the ACW will open immediately if a possible continuation is found.
-
-If there is only one possible completion for the characters entered, a
-:kbd:`Tab` will supply that completion without opening the ACW.
-
-'Show Completions' will force open a completions window, by default the
-:kbd:`C-space` will open a completions window. In an empty
-string, this will contain the files in the current directory. On a
-blank line, it will contain the built-in and user-defined functions and
-classes in the current namespaces, plus any modules imported. If some
-characters have been entered, the ACW will attempt to be more specific.
-
-If a string of characters is typed, the ACW selection will jump to the
-entry most closely matching those characters. Entering a :kbd:`tab` will
-cause the longest non-ambiguous match to be entered in the Editor window or
-Shell. Two :kbd:`tab` in a row will supply the current ACW selection, as
-will return or a double click. Cursor keys, Page Up/Down, mouse selection,
-and the scroll wheel all operate on the ACW.
-
-"Hidden" attributes can be accessed by typing the beginning of hidden
-name after a '.', e.g. '_'. This allows access to modules with
-``__all__`` set, or to class-private attributes.
-
-Completions and the 'Expand Word' facility can save a lot of typing!
-
-Completions are currently limited to those in the namespaces. Names in
-an Editor window which are not via ``__main__`` and :data:`sys.modules` will
-not be found. Run the module once with your imports to correct this situation.
-Note that IDLE itself places quite a few modules in sys.modules, so
-much can be found by default, e.g. the re module.
-
-If you don't like the ACW popping up unbidden, simply make the delay
-longer or disable the extension.
+Completions are supplied, when requested and available, for module
+names, attributes of classes or functions, or filenames. Each request
+method displays a completion box with existing names. (See tab
+completions below for an exception.) For any box, change the name
+being completed and the item highlighted in the box by
+typing and deleting characters; by hitting :kbd:`Up`, :kbd:`Down`,
+:kbd:`PageUp`, :kbd:`PageDown`, :kbd:`Home`, and :kbd:`End` keys;
+and by a single click within the box. Close the box with :kbd:`Escape`,
+:kbd:`Enter`, and double :kbd:`Tab` keys or clicks outside the box.
+A double click within the box selects and closes.
+
+One way to open a box is to type a key character and wait for a
+predefined interval. This defaults to 2 seconds; customize it
+in the settings dialog. (To prevent auto popups, set the delay to a
+large number of milliseconds, such as 100000000.) For imported module
+names or class or function attributes, type '.'.
+For filenames in the root directory, type :data:`os.sep` or
+data:`os.altsep` immediately after an opening quote. (On Windows,
+one can specify a drive first.) Move into subdirectories by typing a
+directory name and a separator.
+
+Instead of waiting, or after a box is closed, open a completion box
+immediately with Show Completions on the Edit menu. The default hot
+key is :kbd:`C-space`. If one types a prefix for the desired name
+before opening the box, the first match or near miss is made visible.
+The result is the same as if one enters a prefix
+after the box is displayed. Show Completions after a quote completes
+filenames in the current directory instead of a root directory.
+
+Hitting :kbd:`Tab` after a prefix usually has the same effect as Show
+Completions. (With no prefix, it indents.) However, if there is only
+one match to the prefix, that match is immediately added to the editor
+text without opening a box.
+
+Invoking 'Show Completions', or hitting :kbd:`Tab` after a prefix,
+outside of a string and without a preceding '.' opens a box with
+keywords, builtin names, and available module-level names.
+
+When editing code in an editor (as oppose to Shell), increase the
+available module-level names by running your code
+and not restarting the Shell thereafter. This is especially useful
+after adding imports at the top of a file. This also increases
+possible attribute completions.
+
+Completion boxes intially exclude names beginning with '_' or, for
+modules, not included in '__all__'. The hidden names can be accessed
+by typing '_' after '.', either before or after the box is opened.
.. _calltips:
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/itertools.rst b/Doc/library/itertools.rst
index 3e5a6738..134afbe6 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -199,9 +199,9 @@ loops that truncate the stream.
Return *r* length subsequences of elements from the input *iterable*.
- Combinations are emitted in lexicographic sort order. So, if the
- input *iterable* is sorted, the combination tuples will be produced
- in sorted order.
+ The combination tuples are emitted in lexicographic ordering according to
+ the order of the input *iterable*. So, if the input *iterable* is sorted,
+ the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their
value. So if the input elements are unique, there will be no repeat
@@ -248,9 +248,9 @@ loops that truncate the stream.
Return *r* length subsequences of elements from the input *iterable*
allowing individual elements to be repeated more than once.
- Combinations are emitted in lexicographic sort order. So, if the
- input *iterable* is sorted, the combination tuples will be produced
- in sorted order.
+ The combination tuples are emitted in lexicographic ordering according to
+ the order of the input *iterable*. So, if the input *iterable* is sorted,
+ the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their
value. So if the input elements are unique, the generated combinations
@@ -484,9 +484,9 @@ loops that truncate the stream.
of the *iterable* and all possible full-length permutations
are generated.
- Permutations are emitted in lexicographic sort order. So, if the
- input *iterable* is sorted, the permutation tuples will be produced
- in sorted order.
+ The permutation tuples are emitted in lexicographic ordering according to
+ the order of the input *iterable*. So, if the input *iterable* is sorted,
+ the combination tuples will be produced in sorted order.
Elements are treated as unique based on their position, not on their
value. So if the input elements are unique, there will be no repeat
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/pdb.rst b/Doc/library/pdb.rst
index 5ee7faaa..ca0a507a 100644
--- a/Doc/library/pdb.rst
+++ b/Doc/library/pdb.rst
@@ -538,6 +538,7 @@ by the local file.
executed in the current environment).
.. pdbcommand:: retval
+
Print the return value for the last return of a function.
.. rubric:: Footnotes
diff --git a/Doc/library/select.rst b/Doc/library/select.rst
index 8f5a2cea..39622aad 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 bd24de72..25b749e5 100644
--- a/Doc/library/shutil.rst
+++ b/Doc/library/shutil.rst
@@ -567,12 +567,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.
@@ -724,6 +726,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/ssl.rst b/Doc/library/ssl.rst
index 4142e41d..ea0f13c4 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -2486,14 +2486,17 @@ provided.
- :meth:`~SSLSocket.read`
- :meth:`~SSLSocket.write`
- :meth:`~SSLSocket.getpeercert`
+ - :meth:`~SSLSocket.selected_alpn_protocol`
- :meth:`~SSLSocket.selected_npn_protocol`
- :meth:`~SSLSocket.cipher`
- :meth:`~SSLSocket.shared_ciphers`
- :meth:`~SSLSocket.compression`
- :meth:`~SSLSocket.pending`
- :meth:`~SSLSocket.do_handshake`
+ - :meth:`~SSLSocket.verify_client_post_handshake`
- :meth:`~SSLSocket.unwrap`
- :meth:`~SSLSocket.get_channel_binding`
+ - :meth:`~SSLSocket.version`
When compared to :class:`SSLSocket`, this object lacks the following
features:
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index 8cc57c30..ccd2f99c 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -434,12 +434,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 cce7da1c..a93a6c18 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.
@@ -704,10 +704,11 @@ Instances of the :class:`Popen` class have the following methods:
.. method:: Popen.communicate(input=None, timeout=None)
Interact with process: Send data to stdin. Read data from stdout and stderr,
- until end-of-file is reached. Wait for process to terminate. The optional
- *input* argument should be data to be sent to the child process, or
- ``None``, if no data should be sent to the child. If streams were opened in
- text mode, *input* must be a string. Otherwise, it must be bytes.
+ until end-of-file is reached. Wait for process to terminate and set the
+ :attr:`~Popen.returncode` attribute. The optional *input* argument should be
+ data to be sent to the child process, or ``None``, if no data should be sent
+ to the child. If streams were opened in text mode, *input* must be a string.
+ Otherwise, it must be bytes.
:meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``.
The data will be strings if streams were opened in text mode; otherwise,
@@ -755,14 +756,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`.
@@ -1049,7 +1050,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.
@@ -1075,7 +1077,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
@@ -1106,7 +1110,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 c34f2c4a..d60f1c8a 100644
--- a/Doc/library/tarfile.rst
+++ b/Doc/library/tarfile.rst
@@ -784,7 +784,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/typing.rst b/Doc/library/typing.rst
index 7269e181..1467276d 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -672,7 +672,7 @@ The module defines the following classes, functions and decorators:
A generic version of :class:`collections.abc.ByteString`.
This type represents the types :class:`bytes`, :class:`bytearray`,
- and :class:`memoryview`.
+ and :class:`memoryview` of byte sequences.
As a shorthand for this type, :class:`bytes` can be used to
annotate arguments of any of the types mentioned above.
@@ -1020,9 +1020,9 @@ The module defines the following classes, functions and decorators:
``List[ForwardRef("SomeClass")]``. This class should not be instantiated by
a user, but may be used by introspection tools.
-.. function:: NewType(typ)
+.. function:: NewType(name, tp)
- A helper function to indicate a distinct types to a typechecker,
+ A helper function to indicate a distinct type to a typechecker,
see :ref:`distinct`. At runtime it returns a function that returns
its argument. Usage::
diff --git a/Doc/library/venv.rst b/Doc/library/venv.rst
index 31a3f41e..59b25183 100644
--- a/Doc/library/venv.rst
+++ b/Doc/library/venv.rst
@@ -27,7 +27,7 @@ See :pep:`405` for more information about Python virtual environments.
.. seealso::
`Python Packaging User Guide: Creating and using virtual environments
- `__
+ `__
Creating virtual environments
diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst
index 2dbe5e33..0d9f21d2 100644
--- a/Doc/library/weakref.rst
+++ b/Doc/library/weakref.rst
@@ -163,13 +163,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
@@ -189,13 +182,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/make.bat b/Doc/make.bat
index a2f64ffd..d621bd16 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/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst
index 844bd7cc..d0e7fde0 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:
diff --git a/Doc/tools/extensions/pyspecific.py b/Doc/tools/extensions/pyspecific.py
index 2d956124..a128c705 100644
--- a/Doc/tools/extensions/pyspecific.py
+++ b/Doc/tools/extensions/pyspecific.py
@@ -311,7 +311,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()
@@ -319,7 +320,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/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 4730a5fe..7a40be77 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 06bdd0d9..250d2a9d 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -114,8 +114,8 @@ accessible. "Directly accessible" here means that an unqualified reference to a
name attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically. At any
-time during execution, there are at least three nested scopes whose namespaces
-are directly accessible:
+time during execution, At any time during execution, there are 3 or 4 nested
+scopes whose namespaces are directly accessible:
* the innermost scope, which is searched first, contains the local names
* the scopes of any enclosing functions, which are searched starting with the
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index f05f5edd..de2c73a3 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -297,11 +297,10 @@ passed using *call by value* (where the *value* is always an object *reference*,
not the value of the object). [#]_ When a function calls another function, a new
local symbol table is created for that call.
-A function definition introduces the function name in the current symbol table.
-The value of the function name has a type that is recognized by the interpreter
-as a user-defined function. This value can be assigned to another name which
-can then also be used as a function. This serves as a general renaming
-mechanism::
+A function definition associates the function name with the function object in
+the current symbol table. The interpreter recognizes the object pointed to by
+that name as a user-defined function. Other names can also point to that same
+function object and can also be used to access the function::
>>> fib
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index a404f4be..366a532e 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 b411fa28..0253625f 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.8` 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/venv-create.inc b/Doc/using/venv-create.inc
index 99b2a19a..c81aaf15 100644
--- a/Doc/using/venv-create.inc
+++ b/Doc/using/venv-create.inc
@@ -86,7 +86,7 @@ The command, if run with ``-h``, will show the available options::
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
See `About Execution Policies
- `_
+ `_
for more information.
The created ``pyvenv.cfg`` file also includes the
diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst
index 636f48df..5114a26a 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/Doc/whatsnew/3.0.rst b/Doc/whatsnew/3.0.rst
index 6b8bd886..880958d3 100644
--- a/Doc/whatsnew/3.0.rst
+++ b/Doc/whatsnew/3.0.rst
@@ -2,8 +2,6 @@
What's New In Python 3.0
****************************
-TEST CHANGE TO BE UNDONE
-
.. XXX Add trademark info for Apple, Microsoft.
:Author: Guido van Rossum
diff --git a/Include/internal/pycore_pystate.h b/Include/internal/pycore_pystate.h
index f90e7e1a..96d5e31d 100644
--- a/Include/internal/pycore_pystate.h
+++ b/Include/internal/pycore_pystate.h
@@ -317,6 +317,9 @@ PyAPI_FUNC(void) _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime);
PyAPI_FUNC(void) _PyGILState_Reinit(_PyRuntimeState *runtime);
+
+PyAPI_FUNC(int) _PyOS_InterruptOccurred(PyThreadState *tstate);
+
#ifdef __cplusplus
}
#endif
diff --git a/Include/patchlevel.h b/Include/patchlevel.h
index 2f6a68fb..41901a58 100644
--- a/Include/patchlevel.h
+++ b/Include/patchlevel.h
@@ -18,12 +18,12 @@
/*--start constants--*/
#define PY_MAJOR_VERSION 3
#define PY_MINOR_VERSION 8
-#define PY_MICRO_VERSION 3
+#define PY_MICRO_VERSION 4
#define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL
#define PY_RELEASE_SERIAL 0
/* Version as a string */
-#define PY_VERSION "3.8.3"
+#define PY_VERSION "3.8.4"
/*--end constants--*/
/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
diff --git a/Lib/ast.py b/Lib/ast.py
index 0c88bcf4..99a1148a 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -483,6 +483,13 @@ class _ABC(type):
return type.__instancecheck__(cls, inst)
def _new(cls, *args, **kwargs):
+ for key in kwargs:
+ if key not in cls._fields:
+ # arbitrary keyword arguments are accepted
+ continue
+ pos = cls._fields.index(key)
+ if pos < len(args):
+ raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
if cls in _const_types:
return Constant(*args, **kwargs)
return Constant.__new__(cls, *args, **kwargs)
diff --git a/Lib/asyncio/unix_events.py b/Lib/asyncio/unix_events.py
index 8c0a5748..1ff8c427 100644
--- a/Lib/asyncio/unix_events.py
+++ b/Lib/asyncio/unix_events.py
@@ -101,7 +101,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 c22c71b3..77ab703c 100755
--- a/Lib/cgi.py
+++ b/Lib/cgi.py
@@ -200,7 +200,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}
@@ -736,7 +739,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..d8e9c5a7 100644
--- a/Lib/ctypes/test/test_callbacks.py
+++ b/Lib/ctypes/test/test_callbacks.py
@@ -1,5 +1,7 @@
import functools
import unittest
+from test import support
+
from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test
@@ -287,7 +289,36 @@ 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)
+
+ def test_convert_result_error(self):
+ def func():
+ return ("tuple",)
+
+ proto = CFUNCTYPE(c_int)
+ ctypes_func = proto(func)
+ with support.catch_unraisable_exception() as cm:
+ # don't test the result since it is an uninitialized value
+ result = ctypes_func()
+
+ self.assertIsInstance(cm.unraisable.exc_value, TypeError)
+ self.assertEqual(cm.unraisable.err_msg,
+ "Exception ignored on converting result "
+ "of ctypes callback function")
+ self.assertIs(cm.unraisable.object, func)
+
if __name__ == '__main__':
unittest.main()
diff --git a/Lib/ctypes/test/test_loading.py b/Lib/ctypes/test/test_loading.py
index a62044e3..5c48b0db 100644
--- a/Lib/ctypes/test/test_loading.py
+++ b/Lib/ctypes/test/test_loading.py
@@ -158,11 +158,9 @@ class LoaderTest(unittest.TestCase):
# Relative path (but not just filename) should succeed
should_pass("WinDLL('./_sqlite3.dll')")
- # XXX: This test has started failing on Azure Pipelines CI. See
- # bpo-40214 for more information.
- if 0:
- # Insecure load flags should succeed
- should_pass("WinDLL('_sqlite3.dll', winmode=0)")
+ # Insecure load flags should succeed
+ # Clear the DLL directory to avoid safe search settings propagating
+ should_pass("windll.kernel32.SetDllDirectoryW(None); WinDLL('_sqlite3.dll', winmode=0)")
# Full path load without DLL_LOAD_DIR shouldn't find dependency
should_fail("WinDLL(nt._getfullpathname('_sqlite3.dll'), " +
diff --git a/Lib/ctypes/test/test_random_things.py b/Lib/ctypes/test/test_random_things.py
index ee5b2128..2988e275 100644
--- a/Lib/ctypes/test/test_random_things.py
+++ b/Lib/ctypes/test/test_random_things.py
@@ -1,5 +1,9 @@
from ctypes import *
-import unittest, sys
+import contextlib
+from test import support
+import unittest
+import sys
+
def callback_func(arg):
42 / arg
@@ -34,41 +38,40 @@ class CallbackTracbackTestCase(unittest.TestCase):
# created, then a full traceback printed. When SystemExit is
# raised in a callback function, the interpreter exits.
- def capture_stderr(self, func, *args, **kw):
- # helper - call function 'func', and return the captured stderr
- import io
- old_stderr = sys.stderr
- logger = sys.stderr = io.StringIO()
- try:
- func(*args, **kw)
- finally:
- sys.stderr = old_stderr
- return logger.getvalue()
+ @contextlib.contextmanager
+ def expect_unraisable(self, exc_type, exc_msg=None):
+ with support.catch_unraisable_exception() as cm:
+ yield
+
+ self.assertIsInstance(cm.unraisable.exc_value, exc_type)
+ if exc_msg is not None:
+ self.assertEqual(str(cm.unraisable.exc_value), exc_msg)
+ self.assertEqual(cm.unraisable.err_msg,
+ "Exception ignored on calling ctypes "
+ "callback function")
+ self.assertIs(cm.unraisable.object, callback_func)
def test_ValueError(self):
cb = CFUNCTYPE(c_int, c_int)(callback_func)
- out = self.capture_stderr(cb, 42)
- self.assertEqual(out.splitlines()[-1],
- "ValueError: 42")
+ with self.expect_unraisable(ValueError, '42'):
+ cb(42)
def test_IntegerDivisionError(self):
cb = CFUNCTYPE(c_int, c_int)(callback_func)
- out = self.capture_stderr(cb, 0)
- self.assertEqual(out.splitlines()[-1][:19],
- "ZeroDivisionError: ")
+ with self.expect_unraisable(ZeroDivisionError):
+ cb(0)
def test_FloatDivisionError(self):
cb = CFUNCTYPE(c_int, c_double)(callback_func)
- out = self.capture_stderr(cb, 0.0)
- self.assertEqual(out.splitlines()[-1][:19],
- "ZeroDivisionError: ")
+ with self.expect_unraisable(ZeroDivisionError):
+ cb(0.0)
def test_TypeErrorDivisionError(self):
cb = CFUNCTYPE(c_int, c_char_p)(callback_func)
- out = self.capture_stderr(cb, b"spam")
- self.assertEqual(out.splitlines()[-1],
- "TypeError: "
- "unsupported operand type(s) for /: 'int' and 'bytes'")
+ err_msg = "unsupported operand type(s) for /: 'int' and 'bytes'"
+ with self.expect_unraisable(TypeError, err_msg):
+ cb(b"spam")
+
if __name__ == '__main__':
unittest.main()
diff --git a/Lib/ctypes/test/test_unaligned_structures.py b/Lib/ctypes/test/test_unaligned_structures.py
index bcacfc81..ee7fb458 100644
--- a/Lib/ctypes/test/test_unaligned_structures.py
+++ b/Lib/ctypes/test/test_unaligned_structures.py
@@ -27,7 +27,6 @@ for typ in [c_short, c_int, c_long, c_longlong,
class TestStructures(unittest.TestCase):
def test_native(self):
for typ in structures:
-## print typ.value
self.assertEqual(typ.value.offset, 1)
o = typ()
o.value = 4
@@ -35,7 +34,6 @@ class TestStructures(unittest.TestCase):
def test_swapped(self):
for typ in byteswapped_structures:
-## print >> sys.stderr, typ.value
self.assertEqual(typ.value.offset, 1)
o = typ()
o.value = 4
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 74f79294..10bb33e3 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1092,7 +1092,7 @@ def _asdict_inner(obj, dict_factory):
# method, because:
# - it does not recurse in to the namedtuple fields and
# convert them to dicts (using dict_factory).
- # - I don't actually want to return a dict here. The the main
+ # - I don't actually want to return a dict here. The main
# use case here is json.dumps, and it handles converting
# namedtuples to lists. Admittedly we're losing some
# information here when we produce a json list instead of a
diff --git a/Lib/distutils/command/build_py.py b/Lib/distutils/command/build_py.py
index cf0ca57c..edc2171c 100644
--- a/Lib/distutils/command/build_py.py
+++ b/Lib/distutils/command/build_py.py
@@ -5,7 +5,7 @@ Implements the Distutils 'build_py' command."""
import os
import importlib.util
import sys
-from glob import glob
+import glob
from distutils.core import Command
from distutils.errors import *
@@ -125,7 +125,7 @@ class build_py (Command):
files = []
for pattern in globs:
# Each pattern has to be converted to a platform-specific path
- filelist = glob(os.path.join(src_dir, convert_path(pattern)))
+ filelist = glob.glob(os.path.join(glob.escape(src_dir), convert_path(pattern)))
# Files that match more than one pattern are only added once
files.extend([fn for fn in filelist if fn not in files
and os.path.isfile(fn)])
@@ -216,7 +216,7 @@ class build_py (Command):
def find_package_modules(self, package, package_dir):
self.check_package(package, package_dir)
- module_files = glob(os.path.join(package_dir, "*.py"))
+ module_files = glob.glob(os.path.join(glob.escape(package_dir), "*.py"))
modules = []
setup_script = os.path.abspath(self.distribution.script_name)
diff --git a/Lib/distutils/tests/__init__.py b/Lib/distutils/tests/__init__.py
index 1b939cbd..68037216 100644
--- a/Lib/distutils/tests/__init__.py
+++ b/Lib/distutils/tests/__init__.py
@@ -15,7 +15,7 @@ by import rather than matching pre-defined names.
import os
import sys
import unittest
-from test.support import run_unittest
+from test.support import run_unittest, save_restore_warnings_filters
here = os.path.dirname(__file__) or os.curdir
@@ -26,7 +26,11 @@ def test_suite():
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
modname = "distutils.tests." + fn[:-3]
- __import__(modname)
+ # bpo-40055: Save/restore warnings filters to leave them unchanged.
+ # Importing tests imports docutils which imports pkg_resources
+ # which adds a warnings filter.
+ with save_restore_warnings_filters():
+ __import__(modname)
module = sys.modules[modname]
suite.addTest(module.test_suite())
return suite
diff --git a/Lib/email/_header_value_parser.py b/Lib/email/_header_value_parser.py
index 9c55ef7f..51d355fb 100644
--- a/Lib/email/_header_value_parser.py
+++ b/Lib/email/_header_value_parser.py
@@ -1218,12 +1218,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/contentmanager.py b/Lib/email/contentmanager.py
index b904ded9..b91fb0e5 100644
--- a/Lib/email/contentmanager.py
+++ b/Lib/email/contentmanager.py
@@ -146,13 +146,13 @@ def _encode_text(string, charset, cte, policy):
def normal_body(lines): return b'\n'.join(lines) + b'\n'
if cte==None:
# Use heuristics to decide on the "best" encoding.
- try:
- return '7bit', normal_body(lines).decode('ascii')
- except UnicodeDecodeError:
- pass
- if (policy.cte_type == '8bit' and
- max(len(x) for x in lines) <= policy.max_line_length):
- return '8bit', normal_body(lines).decode('ascii', 'surrogateescape')
+ if max((len(x) for x in lines), default=0) <= policy.max_line_length:
+ try:
+ return '7bit', normal_body(lines).decode('ascii')
+ except UnicodeDecodeError:
+ pass
+ if policy.cte_type == '8bit':
+ return '8bit', normal_body(lines).decode('ascii', 'surrogateescape')
sniff = embedded_body(lines[:10])
sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'),
policy.max_line_length)
diff --git a/Lib/email/headerregistry.py b/Lib/email/headerregistry.py
index 8d1a2025..d0914fd1 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/email/utils.py b/Lib/email/utils.py
index 858f620e..07dd029c 100644
--- a/Lib/email/utils.py
+++ b/Lib/email/utils.py
@@ -81,7 +81,7 @@ def formataddr(pair, charset='utf-8'):
If the first element of pair is false, then the second element is
returned unmodified.
- Optional charset if given is the character set that is used to encode
+ The optional charset is the character set that is used to encode
realname in case realname is not ASCII safe. Can be an instance of str or
a Charset-like object which has a header_encode method. Default is
'utf-8'.
diff --git a/Lib/ensurepip/__init__.py b/Lib/ensurepip/__init__.py
index 566fb2a0..f3152a55 100644
--- a/Lib/ensurepip/__init__.py
+++ b/Lib/ensurepip/__init__.py
@@ -9,13 +9,13 @@ 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"),
]
@@ -104,8 +104,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),
@@ -116,7 +116,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 108d389d..14cc00e7 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -60,6 +60,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.
@@ -77,6 +78,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):
@@ -100,6 +104,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/idlelib/NEWS.txt b/Lib/idlelib/NEWS.txt
index de7543e3..b43c6d3a 100644
--- a/Lib/idlelib/NEWS.txt
+++ b/Lib/idlelib/NEWS.txt
@@ -1,16 +1,33 @@
-What's New in IDLE 3.8.1
-Released on 2019-12-16?
+What's New in IDLE 3.8.4
+Released on 2020-07-03?
======================================
+bpo-37765: Add keywords to module name completion list. Rewrite
+Completions section of IDLE doc.
+
+bpo-41152: The encoding of ``stdin``, ``stdout`` and ``stderr`` in IDLE
+is now always UTF-8.
+
+bpo-41144: Make Open Module open a special module such as os.path.
+
+bpo-40723: Make test_idle pass when run after import.
+Patch by Florian Dahlitz.
+
+
+What's New in IDLE 3.8.3
+Released on 2020-05-13
+======================================
+
bpo-38689: IDLE will no longer freeze when inspect.signature fails
when fetching a calltip.
bpo-27115: For 'Go to Line', use a Query entry box subclass with
IDLE standard behavior and improved error checking.
-bpo-39885: Since clicking to get an IDLE context menu moves the
-cursor, any text selection should be and now is cleared.
+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.
@@ -19,6 +36,11 @@ bpo-39781: Selecting code context lines no longer causes a jump.
bpo-39663: Add tests for pyparse find_good_parse_start().
+
+What's New in IDLE 3.8.2
+Released on 2020-02-17
+======================================
+
bpo-39600: Remove duplicate font names from configuration list.
bpo-38792: Close a shell calltip if a :exc:`KeyboardInterrupt`
@@ -35,6 +57,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.8.1
+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.py b/Lib/idlelib/autocomplete.py
index c623d45a..e1e9e173 100644
--- a/Lib/idlelib/autocomplete.py
+++ b/Lib/idlelib/autocomplete.py
@@ -4,6 +4,7 @@ Either on demand or after a user-selected delay after a key character,
pop up a list of candidates.
"""
import __main__
+import keyword
import os
import string
import sys
@@ -171,10 +172,13 @@ class AutoComplete:
(what, mode), {})
else:
if mode == ATTRS:
- if what == "":
+ if what == "": # Main module names.
namespace = {**__main__.__builtins__.__dict__,
**__main__.__dict__}
bigl = eval("dir()", namespace)
+ kwds = (s for s in keyword.kwlist
+ if s not in {'True', 'False', 'None'})
+ bigl.extend(kwds)
bigl.sort()
if "__all__" in bigl:
smalll = sorted(eval("__all__", namespace))
diff --git a/Lib/idlelib/editor.py b/Lib/idlelib/editor.py
index b0f88b54..a178eaf9 100644
--- a/Lib/idlelib/editor.py
+++ b/Lib/idlelib/editor.py
@@ -499,15 +499,23 @@ class EditorWindow(object):
rmenu = None
def right_menu_event(self, event):
- self.text.tag_remove("sel", "1.0", "end")
- 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:
@@ -520,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")
diff --git a/Lib/idlelib/help.html b/Lib/idlelib/help.html
index 424c6b50..81ce5100 100644
--- a/Lib/idlelib/help.html
+++ b/Lib/idlelib/help.html
@@ -4,7 +4,7 @@
- IDLE — Python 3.9.0a4 documentation
+ IDLE — Python 3.10.0a0 documentation
@@ -17,7 +17,7 @@
@@ -71,7 +71,7 @@
Completions are supplied for functions, classes, and attributes of classes,
-both built-in and user-defined. Completions are also provided for
-filenames.
-
The AutoCompleteWindow (ACW) will open after a predefined delay (default is
-two seconds) after a â.â or (in a string) an os.sep is typed. If after one
-of those characters (plus zero or more other characters) a tab is typed
-the ACW will open immediately if a possible continuation is found.
-
If there is only one possible completion for the characters entered, a
-Tab will supply that completion without opening the ACW.
-
âShow Completionsâ will force open a completions window, by default the
-C-space will open a completions window. In an empty
-string, this will contain the files in the current directory. On a
-blank line, it will contain the built-in and user-defined functions and
-classes in the current namespaces, plus any modules imported. If some
-characters have been entered, the ACW will attempt to be more specific.
-
If a string of characters is typed, the ACW selection will jump to the
-entry most closely matching those characters. Entering a tab will
-cause the longest non-ambiguous match to be entered in the Editor window or
-Shell. Two tab in a row will supply the current ACW selection, as
-will return or a double click. Cursor keys, Page Up/Down, mouse selection,
-and the scroll wheel all operate on the ACW.
-
âHiddenâ attributes can be accessed by typing the beginning of hidden
-name after a â.â, e.g. â_â. This allows access to modules with
-__all__ set, or to class-private attributes.
-
Completions and the âExpand Wordâ facility can save a lot of typing!
-
Completions are currently limited to those in the namespaces. Names in
-an Editor window which are not via __main__ and sys.modules will
-not be found. Run the module once with your imports to correct this situation.
-Note that IDLE itself places quite a few modules in sys.modules, so
-much can be found by default, e.g. the re module.
-
If you donât like the ACW popping up unbidden, simply make the delay
-longer or disable the extension.
+
Completions are supplied, when requested and available, for module
+names, attributes of classes or functions, or filenames. Each request
+method displays a completion box with existing names. (See tab
+completions below for an exception.) For any box, change the name
+being completed and the item highlighted in the box by
+typing and deleting characters; by hitting Up, Down,
+PageUp, PageDown, Home, and End keys;
+and by a single click within the box. Close the box with Escape,
+Enter, and double Tab keys or clicks outside the box.
+A double click within the box selects and closes.
+
One way to open a box is to type a key character and wait for a
+predefined interval. This defaults to 2 seconds; customize it
+in the settings dialog. (To prevent auto popups, set the delay to a
+large number of milliseconds, such as 100000000.) For imported module
+names or class or function attributes, type â.â.
+For filenames in the root directory, type os.sep or
+data:os.altsep immediately after an opening quote. (On Windows,
+one can specify a drive first.) Move into subdirectories by typing a
+directory name and a separator.
+
Instead of waiting, or after a box is closed. open a completion box
+immediately with Show Completions on the Edit menu. The default hot
+key is C-space. If one types a prefix for the desired name
+before opening the box, the first match is displayed.
+The result is the same as if one enters a prefix
+after the box is displayed. Show Completions after a quote completes
+filenames in the current directory instead of a root directory.
+
Hitting Tab after a prefix usually has the same effect as Show
+Completions. (With no prefix, it indents.) However, if there is only
+one match to the prefix, that match is immediately added to the editor
+text without opening a box.
+
Invoking âShow Completionsâ, or hitting Tab after a prefix,
+outside of a string and without a preceding â.â opens a box with
+keywords, builtin names, and available module-level names.
+
When editing code in an editor (as oppose to Shell), increase the
+available module-level names by running your code
+and not restarting the Shell thereafter. This is especially useful
+after adding imports at the top of a file. This also increases
+possible attribute completions.
+
Completion boxes intially exclude names beginning with â_â or, for
+modules, not included in â__all__â. The hidden names can be accessed
+by typing â_â after â.â, either before or after the box is opened.