diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst
index 513ef93a384202..9b7383373e9841 100644
--- a/Doc/c-api/init.rst
+++ b/Doc/c-api/init.rst
@@ -1929,7 +1929,7 @@ is not possible due to its implementation being opaque at build time.
Free the given *key* allocated by :c:func:`PyThread_tss_alloc`, after
first calling :c:func:`PyThread_tss_delete` to ensure any associated
thread locals have been unassigned. This is a no-op if the *key*
- argument is `NULL`.
+ argument is ``NULL``.
.. note::
A freed key becomes a dangling pointer. You should reset the key to
diff --git a/Doc/c-api/type.rst b/Doc/c-api/type.rst
index deb5502a4dff9e..1dc05001adfa37 100644
--- a/Doc/c-api/type.rst
+++ b/Doc/c-api/type.rst
@@ -40,7 +40,7 @@ Type Objects
.. c:function:: unsigned long PyType_GetFlags(PyTypeObject* type)
Return the :c:member:`~PyTypeObject.tp_flags` member of *type*. This function is primarily
- meant for use with `Py_LIMITED_API`; the individual flag bits are
+ meant for use with ``Py_LIMITED_API``; the individual flag bits are
guaranteed to be stable across Python releases, but access to
:c:member:`~PyTypeObject.tp_flags` itself is not part of the limited API.
diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst
index 52388fca5cdbca..ccdc9bf02b1c7b 100644
--- a/Doc/faq/design.rst
+++ b/Doc/faq/design.rst
@@ -155,7 +155,7 @@ Why can't I use an assignment in an expression?
Starting in Python 3.8, you can!
-Assignment expressions using the walrus operator `:=` assign a variable in an
+Assignment expressions using the walrus operator ``:=`` assign a variable in an
expression::
while chunk := fp.read(200):
diff --git a/Doc/howto/enum.rst b/Doc/howto/enum.rst
index 376934a0e79365..03f05657997cfd 100644
--- a/Doc/howto/enum.rst
+++ b/Doc/howto/enum.rst
@@ -1109,7 +1109,7 @@ Enum Classes
The :class:`EnumType` metaclass is responsible for providing the
:meth:`__contains__`, :meth:`__dir__`, :meth:`__iter__` and other methods that
allow one to do things with an :class:`Enum` class that fail on a typical
-class, such as `list(Color)` or `some_enum_var in Color`. :class:`EnumType` is
+class, such as ``list(Color)`` or ``some_enum_var in Color``. :class:`EnumType` is
responsible for ensuring that various other methods on the final :class:`Enum`
class are correct (such as :meth:`__new__`, :meth:`__getnewargs__`,
:meth:`__str__` and :meth:`__repr__`).
diff --git a/Doc/howto/logging-cookbook.rst b/Doc/howto/logging-cookbook.rst
index ff7ba0789608ff..913502eba76434 100644
--- a/Doc/howto/logging-cookbook.rst
+++ b/Doc/howto/logging-cookbook.rst
@@ -562,7 +562,7 @@ To run a logging listener in production, you may need to use a process-managemen
such as `Supervisor `_. `Here
`_ is a Gist which
provides the bare-bones files to run the above functionality using Supervisor: you
-will need to change the `/path/to/` parts in the Gist to reflect the actual paths you
+will need to change the ``/path/to/`` parts in the Gist to reflect the actual paths you
want to use.
@@ -2774,7 +2774,7 @@ Formatting times using UTC (GMT) via configuration
--------------------------------------------------
Sometimes you want to format times using UTC, which can be done using a class
-such as `UTCFormatter`, shown below::
+such as ``UTCFormatter``, shown below::
import logging
import time
diff --git a/Doc/howto/logging.rst b/Doc/howto/logging.rst
index 0caff13bd15d82..145449b2dfbd9f 100644
--- a/Doc/howto/logging.rst
+++ b/Doc/howto/logging.rst
@@ -555,14 +555,14 @@ raw message. If there is no date format string, the default date format is:
%Y-%m-%d %H:%M:%S
-with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
-or '$'. If one of these is not specified, then '%' will be used.
+with the milliseconds tacked on at the end. The ``style`` is one of ``'%'``,
+``'{'``, or ``'$'``. If one of these is not specified, then ``'%'`` will be used.
-If the ``style`` is '%', the message format string uses
+If the ``style`` is ``'%'``, the message format string uses
``%()s`` styled string substitution; the possible keys are
-documented in :ref:`logrecord-attributes`. If the style is '{', the message
+documented in :ref:`logrecord-attributes`. If the style is ``'{'``, the message
format string is assumed to be compatible with :meth:`str.format` (using
-keyword arguments), while if the style is '$' then the message format string
+keyword arguments), while if the style is ``'$'`` then the message format string
should conform to what is expected by :meth:`string.Template.substitute`.
.. versionchanged:: 3.2
diff --git a/Doc/howto/perf_profiling.rst b/Doc/howto/perf_profiling.rst
index ed8de888b3bc21..387fb3ff893561 100644
--- a/Doc/howto/perf_profiling.rst
+++ b/Doc/howto/perf_profiling.rst
@@ -151,7 +151,7 @@ Enabling perf profiling mode
----------------------------
There are two main ways to activate the perf profiling mode. If you want it to be
-active since the start of the Python interpreter, you can use the `-Xperf` option:
+active since the start of the Python interpreter, you can use the ``-Xperf`` option:
$ python -Xperf my_script.py
diff --git a/Doc/install/index.rst b/Doc/install/index.rst
index 3fc670b191424d..ab581d785ef7f0 100644
--- a/Doc/install/index.rst
+++ b/Doc/install/index.rst
@@ -765,7 +765,7 @@ And on Windows, the configuration files are:
+--------------+-------------------------------------------------+-------+
On all platforms, the "personal" file can be temporarily disabled by
-passing the `--no-user-cfg` option.
+passing the ``--no-user-cfg`` option.
Notes:
diff --git a/Doc/library/asyncio-future.rst b/Doc/library/asyncio-future.rst
index 8e60877f0e4c7d..70cec9b2f90248 100644
--- a/Doc/library/asyncio-future.rst
+++ b/Doc/library/asyncio-future.rst
@@ -197,11 +197,6 @@ Future Object
.. versionchanged:: 3.9
Added the *msg* parameter.
- .. deprecated-removed:: 3.11 3.14
- *msg* parameter is ambiguous when multiple :meth:`cancel`
- are called with different cancellation messages.
- The argument will be removed.
-
.. method:: exception()
Return the exception that was set on this Future.
@@ -282,8 +277,3 @@ the Future has a result::
- :meth:`asyncio.Future.cancel` accepts an optional ``msg`` argument,
but :func:`concurrent.futures.cancel` does not.
-
- .. deprecated-removed:: 3.11 3.14
- *msg* parameter is ambiguous when multiple :meth:`cancel`
- are called with different cancellation messages.
- The argument will be removed.
diff --git a/Doc/library/asyncio-protocol.rst b/Doc/library/asyncio-protocol.rst
index 8b67f4b8957ef6..969354ceb163b5 100644
--- a/Doc/library/asyncio-protocol.rst
+++ b/Doc/library/asyncio-protocol.rst
@@ -553,7 +553,7 @@ accept factories that return streaming protocols.
a connection is open.
However, :meth:`protocol.eof_received() `
- is called at most once. Once `eof_received()` is called,
+ is called at most once. Once ``eof_received()`` is called,
``data_received()`` is not called anymore.
.. method:: Protocol.eof_received()
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst
index d922f614954fcd..fb6d23fda03e41 100644
--- a/Doc/library/asyncio-task.rst
+++ b/Doc/library/asyncio-task.rst
@@ -631,7 +631,7 @@ Timeouts
Change the time the timeout will trigger.
- If *when* is `None`, any current deadline will be removed, and the
+ If *when* is ``None``, any current deadline will be removed, and the
context manager will wait indefinitely.
If *when* is a float, it is set as the new deadline.
@@ -867,17 +867,17 @@ Running in Threads
# blocking_io complete at 19:50:54
# finished main at 19:50:54
- Directly calling `blocking_io()` in any coroutine would block the event loop
+ Directly calling ``blocking_io()`` in any coroutine would block the event loop
for its duration, resulting in an additional 1 second of run time. Instead,
- by using `asyncio.to_thread()`, we can run it in a separate thread without
+ by using ``asyncio.to_thread()``, we can run it in a separate thread without
blocking the event loop.
.. note::
- Due to the :term:`GIL`, `asyncio.to_thread()` can typically only be used
+ Due to the :term:`GIL`, ``asyncio.to_thread()`` can typically only be used
to make IO-bound functions non-blocking. However, for extension modules
that release the GIL or alternative Python implementations that don't
- have one, `asyncio.to_thread()` can also be used for CPU-bound functions.
+ have one, ``asyncio.to_thread()`` can also be used for CPU-bound functions.
.. versionadded:: 3.9
@@ -1144,10 +1144,8 @@ Task Object
.. versionchanged:: 3.9
Added the *msg* parameter.
- .. deprecated-removed:: 3.11 3.14
- *msg* parameter is ambiguous when multiple :meth:`cancel`
- are called with different cancellation messages.
- The argument will be removed.
+ .. versionchanged:: 3.11
+ The ``msg`` parameter is propagated from cancelled task to its awaiter.
.. _asyncio_example_task_cancel:
diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst
index 7b74bbd652be38..d201dc963b5995 100644
--- a/Doc/library/bdb.rst
+++ b/Doc/library/bdb.rst
@@ -143,7 +143,7 @@ The :mod:`bdb` module also defines two classes:
For real file names, the canonical form is an operating-system-dependent,
:func:`case-normalized ` :func:`absolute path
- `. A *filename* with angle brackets, such as `""`
+ `. A *filename* with angle brackets, such as ``""``
generated in interactive mode, is returned unchanged.
.. method:: reset()
diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst
index 999892e95f4715..ae5a1598f84b44 100644
--- a/Doc/library/bz2.rst
+++ b/Doc/library/bz2.rst
@@ -206,7 +206,7 @@ Incremental (de)compression
will be set to ``True``.
Attempting to decompress data after the end of stream is reached
- raises an `EOFError`. Any data found after the end of the
+ raises an :exc:`EOFError`. Any data found after the end of the
stream is ignored and saved in the :attr:`~.unused_data` attribute.
.. versionchanged:: 3.5
@@ -303,7 +303,7 @@ Using :class:`BZ2Compressor` for incremental compression:
>>> out = out + comp.flush()
The example above uses a very "nonrandom" stream of data
-(a stream of `b"z"` chunks). Random data tends to compress poorly,
+(a stream of ``b"z"`` chunks). Random data tends to compress poorly,
while ordered, repetitive data usually yields a high compression ratio.
Writing and reading a bzip2-compressed file in binary mode:
diff --git a/Doc/library/concurrent.futures.rst b/Doc/library/concurrent.futures.rst
index 95c9e50991423f..8106cc235e5a3c 100644
--- a/Doc/library/concurrent.futures.rst
+++ b/Doc/library/concurrent.futures.rst
@@ -152,7 +152,7 @@ And::
All threads enqueued to ``ThreadPoolExecutor`` will be joined before the
interpreter can exit. Note that the exit handler which does this is
- executed *before* any exit handlers added using `atexit`. This means
+ executed *before* any exit handlers added using ``atexit``. This means
exceptions in the main thread must be caught and handled in order to
signal threads to exit gracefully. For this reason, it is recommended
that ``ThreadPoolExecutor`` not be used for long-running tasks.
@@ -411,13 +411,13 @@ The :class:`Future` class encapsulates the asynchronous execution of a callable.
tests.
If the method returns ``False`` then the :class:`Future` was cancelled,
- i.e. :meth:`Future.cancel` was called and returned `True`. Any threads
+ i.e. :meth:`Future.cancel` was called and returned ``True``. Any threads
waiting on the :class:`Future` completing (i.e. through
:func:`as_completed` or :func:`wait`) will be woken up.
If the method returns ``True`` then the :class:`Future` was not cancelled
and has been put in the running state, i.e. calls to
- :meth:`Future.running` will return `True`.
+ :meth:`Future.running` will return ``True``.
This method can only be called once and cannot be called after
:meth:`Future.set_result` or :meth:`Future.set_exception` have been
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index 4b6b26c991fd38..0351ec970be0b8 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -1948,7 +1948,7 @@ Utility functions
.. function:: GetLastError()
Windows only: Returns the last error code set by Windows in the calling thread.
- This function calls the Windows `GetLastError()` function directly,
+ This function calls the Windows ``GetLastError()`` function directly,
it does not return the ctypes-private copy of the error code.
.. function:: get_errno()
diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst
index bb203c48f19ffb..bf4e69a0170a62 100644
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -275,7 +275,7 @@ The module :mod:`curses` defines the following functions:
Change the definition of a color, taking the number of the color to be changed
followed by three RGB values (for the amounts of red, green, and blue
components). The value of *color_number* must be between ``0`` and
- `COLORS - 1`. Each of *r*, *g*, *b*, must be a value between ``0`` and
+ ``COLORS - 1``. Each of *r*, *g*, *b*, must be a value between ``0`` and
``1000``. When :func:`init_color` is used, all occurrences of that color on the
screen immediately change to the new definition. This function is a no-op on
most terminals; it is active only if :func:`can_change_color` returns ``True``.
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index c3a66a4674b10a..f7e2bb3f3c6de3 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -1769,7 +1769,7 @@ Other constructor:
ISO 8601 format, with the following exceptions:
1. Time zone offsets may have fractional seconds.
- 2. The leading `T`, normally required in cases where there may be ambiguity between
+ 2. The leading ``T``, normally required in cases where there may be ambiguity between
a date and a time, is not required.
3. Fractional seconds may have any number of digits (anything beyond 6 will
be truncated).
@@ -2265,7 +2265,7 @@ where historical changes have been made to civil time.
two digits of ``offset.hours`` and ``offset.minutes`` respectively.
.. versionchanged:: 3.6
- Name generated from ``offset=timedelta(0)`` is now plain `'UTC'`, not
+ Name generated from ``offset=timedelta(0)`` is now plain ``'UTC'``, not
``'UTC+00:00'``.
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index b7e836308fa8aa..260108136df7f1 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -576,11 +576,11 @@ Decimal objects
Alternative constructor that only accepts instances of :class:`float` or
:class:`int`.
- Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
+ Note ``Decimal.from_float(0.1)`` is not the same as ``Decimal('0.1')``.
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
- `0x1.999999999999ap-4`. That equivalent value in decimal is
- `0.1000000000000000055511151231257827021181583404541015625`.
+ ``0x1.999999999999ap-4``. That equivalent value in decimal is
+ ``0.1000000000000000055511151231257827021181583404541015625``.
.. note:: From Python 3.2 onwards, a :class:`Decimal` instance
can also be constructed directly from a :class:`float`.
@@ -1209,7 +1209,7 @@ In addition to the three supplied contexts, new contexts can be created with the
.. method:: exp(x)
- Returns `e ** x`.
+ Returns ``e ** x``.
.. method:: fma(x, y, z)
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 47e4bf60072170..30a336197c397d 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -367,7 +367,7 @@ details of bytecode instructions as :class:`Instruction` instances:
.. class:: Positions
- In case the information is not available, some fields might be `None`.
+ In case the information is not available, some fields might be ``None``.
.. data:: lineno
.. data:: end_lineno
diff --git a/Doc/library/email.compat32-message.rst b/Doc/library/email.compat32-message.rst
index 4eaa9d588ca35e..5bef155a4af310 100644
--- a/Doc/library/email.compat32-message.rst
+++ b/Doc/library/email.compat32-message.rst
@@ -298,7 +298,7 @@ Here are the methods of the :class:`Message` class:
In a model generated from bytes, any header values that (in contravention of
the RFCs) contain non-ASCII bytes will, when retrieved through this
interface, be represented as :class:`~email.header.Header` objects with
- a charset of `unknown-8bit`.
+ a charset of ``unknown-8bit``.
.. method:: __len__()
diff --git a/Doc/library/email.headerregistry.rst b/Doc/library/email.headerregistry.rst
index 98527cea43da2a..00a954e0307ea6 100644
--- a/Doc/library/email.headerregistry.rst
+++ b/Doc/library/email.headerregistry.rst
@@ -153,7 +153,7 @@ headers.
specified as ``-0000`` (indicating it is in UTC but contains no
information about the source timezone), then :attr:`.datetime` will be a
naive :class:`~datetime.datetime`. If a specific timezone offset is
- found (including `+0000`), then :attr:`.datetime` will contain an aware
+ found (including ``+0000``), then :attr:`.datetime` will contain an aware
``datetime`` that uses :class:`datetime.timezone` to record the timezone
offset.
diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst
index 3751800b3b1118..c46d88b2297aa1 100644
--- a/Doc/library/fractions.rst
+++ b/Doc/library/fractions.rst
@@ -99,7 +99,7 @@ another rational number, or from a string.
``typing.SupportsInt`` instance checks.
.. versionchanged:: 3.12
- Space is allowed around the slash for string inputs: `Fraction('2 / 3')`.
+ Space is allowed around the slash for string inputs: ``Fraction('2 / 3')``.
.. attribute:: numerator
diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst
index 386541acf510ac..8e47312fe77bf5 100644
--- a/Doc/library/hashlib.rst
+++ b/Doc/library/hashlib.rst
@@ -426,7 +426,7 @@ Constructor functions also accept the following tree hashing parameters:
BLAKE2s, 0 in sequential mode).
* *last_node*: boolean indicating whether the processed node is the last
- one (`False` for sequential mode).
+ one (``False`` for sequential mode).
.. figure:: hashlib-blake2-tree.png
:alt: Explanation of tree mode parameters.
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index a7c067c06e8ec2..3fc1531c0cdf19 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -443,7 +443,7 @@ ABC hierarchy::
from the import. If the loader inserted a module and the load fails, it
must be removed by the loader from :data:`sys.modules`; modules already
in :data:`sys.modules` before the loader began execution should be left
- alone (see :func:`importlib.util.module_for_loader`).
+ alone.
The loader should set several attributes on the module
(note that some of these attributes can change when a module is
@@ -1326,58 +1326,6 @@ an :term:`importer`.
.. versionadded:: 3.5
-.. decorator:: module_for_loader
-
- A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
- to handle selecting the proper
- module object to load with. The decorated method is expected to have a call
- signature taking two positional arguments
- (e.g. ``load_module(self, module)``) for which the second argument
- will be the module **object** to be used by the loader.
- Note that the decorator will not work on static methods because of the
- assumption of two arguments.
-
- The decorated method will take in the **name** of the module to be loaded
- as expected for a :term:`loader`. If the module is not found in
- :data:`sys.modules` then a new one is constructed. Regardless of where the
- module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
- is set based on what :meth:`importlib.abc.InspectLoader.is_package` returns
- (if available). These attributes are set unconditionally to support
- reloading.
-
- If an exception is raised by the decorated method and a module was added to
- :data:`sys.modules`, then the module will be removed to prevent a partially
- initialized module from being in left in :data:`sys.modules`. If the module
- was already in :data:`sys.modules` then it is left alone.
-
- .. versionchanged:: 3.3
- :attr:`__loader__` and :attr:`__package__` are automatically set
- (when possible).
-
- .. versionchanged:: 3.4
- Set :attr:`__name__`, :attr:`__loader__` :attr:`__package__`
- unconditionally to support reloading.
-
- .. deprecated:: 3.4
- The import machinery now directly performs all the functionality
- provided by this function.
-
-.. decorator:: set_loader
-
- A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
- to set the :attr:`__loader__`
- attribute on the returned module. If the attribute is already set the
- decorator does nothing. It is assumed that the first positional argument to
- the wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set
- to.
-
- .. versionchanged:: 3.4
- Set ``__loader__`` if set to ``None``, as if the attribute does not
- exist.
-
- .. deprecated:: 3.4
- The import machinery takes care of this automatically.
-
.. function:: spec_from_loader(name, loader, *, origin=None, is_package=None)
A factory function for creating a :class:`~importlib.machinery.ModuleSpec`
diff --git a/Doc/library/io.rst b/Doc/library/io.rst
index 8fd6b3537019aa..0968509fbafec2 100644
--- a/Doc/library/io.rst
+++ b/Doc/library/io.rst
@@ -1055,10 +1055,10 @@ Text I/O
The initial value of the buffer can be set by providing *initial_value*.
If newline translation is enabled, newlines will be encoded as if by
:meth:`~TextIOBase.write`. The stream is positioned at the start of the
- buffer which emulates opening an existing file in a `w+` mode, making it
+ buffer which emulates opening an existing file in a ``w+`` mode, making it
ready for an immediate write from the beginning or for a write that
- would overwrite the initial value. To emulate opening a file in an `a+`
- mode ready for appending, use `f.seek(0, io.SEEK_END)` to reposition the
+ would overwrite the initial value. To emulate opening a file in an ``a+``
+ mode ready for appending, use ``f.seek(0, io.SEEK_END)`` to reposition the
stream at the end of the buffer.
The *newline* argument works like that of :class:`TextIOWrapper`,
diff --git a/Doc/library/lzma.rst b/Doc/library/lzma.rst
index f7aaa0cb30c2a8..a9311f2a03563f 100644
--- a/Doc/library/lzma.rst
+++ b/Doc/library/lzma.rst
@@ -258,7 +258,7 @@ Compressing and decompressing data in memory
will be set to ``True``.
Attempting to decompress data after the end of stream is reached
- raises an `EOFError`. Any data found after the end of the
+ raises an :exc:`EOFError`. Any data found after the end of the
stream is ignored and saved in the :attr:`~.unused_data` attribute.
.. versionchanged:: 3.5
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index cb06dc690b4d07..23b014b0b65924 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -3194,7 +3194,7 @@ features:
system records access and modification times; see :func:`~os.stat`. The best
way to preserve exact times is to use the *st_atime_ns* and *st_mtime_ns*
fields from the :func:`os.stat` result object with the *ns* parameter to
- `utime`.
+ :func:`utime`.
This function can support :ref:`specifying a file descriptor `,
:ref:`paths relative to directory descriptors ` and :ref:`not
@@ -4094,7 +4094,7 @@ written in Python, such as a mail server's external command delivery program.
library :c:data:`POSIX_SPAWN_RESETIDS` flag.
If the *setsid* argument is ``True``, it will create a new session ID
- for `posix_spawn`. *setsid* requires :c:data:`POSIX_SPAWN_SETSID`
+ for ``posix_spawn``. *setsid* requires :c:data:`POSIX_SPAWN_SETSID`
or :c:data:`POSIX_SPAWN_SETSID_NP` flag. Otherwise, :exc:`NotImplementedError`
is raised.
diff --git a/Doc/library/select.rst b/Doc/library/select.rst
index a8df81f5bd1f07..2890706bab729c 100644
--- a/Doc/library/select.rst
+++ b/Doc/library/select.rst
@@ -61,7 +61,7 @@ The module defines the following:
events.
*sizehint* informs epoll about the expected number of events to be
- registered. It must be positive, or `-1` to use the default. It is only
+ registered. It must be positive, or ``-1`` to use the default. It is only
used on older systems where :c:func:`epoll_create1` is not available;
otherwise it has no effect (though its value is still checked).
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
index ee0c68e3a70779..3f6cb480371617 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -689,7 +689,7 @@ The following functions all create :ref:`socket objects `.
When :const:`SOCK_NONBLOCK` or :const:`SOCK_CLOEXEC`
bit flags are applied to *type* they are cleared, and
:attr:`socket.type` will not reflect them. They are still passed
- to the underlying system `socket()` call. Therefore,
+ to the underlying system ``socket()`` call. Therefore,
::
diff --git a/Doc/library/statistics.rst b/Doc/library/statistics.rst
index c3f9c1f5239e8b..88a887960edb58 100644
--- a/Doc/library/statistics.rst
+++ b/Doc/library/statistics.rst
@@ -839,7 +839,7 @@ of applications in statistics.
The relative likelihood is computed as the probability of a sample
occurring in a narrow range divided by the width of the range (hence
the word "density"). Since the likelihood is relative to other points,
- its value can be greater than `1.0`.
+ its value can be greater than ``1.0``.
.. method:: NormalDist.cdf(x)
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index aab3f6aa83fced..542b08b1878ed0 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -250,7 +250,7 @@ always available.
Print low-level information to stderr about the state of CPython's memory
allocator.
- If Python is `built in debug mode ` (:option:`configure
+ If Python is :ref:`built in debug mode ` (:option:`configure
--with-pydebug option <--with-pydebug>`), it also performs some expensive
internal consistency checks.
@@ -349,7 +349,7 @@ always available.
files to (and read them from) a parallel directory tree rooted at this
directory, rather than from ``__pycache__`` directories in the source code
tree. Any ``__pycache__`` directories in the source code tree will be ignored
- and new `.pyc` files written within the pycache prefix. Thus if you use
+ and new ``.pyc`` files written within the pycache prefix. Thus if you use
:mod:`compileall` as a pre-build step, you must ensure you run it with the
same pycache prefix (if any) that you will use at runtime.
@@ -874,7 +874,7 @@ always available.
.. function:: get_asyncgen_hooks()
Returns an *asyncgen_hooks* object, which is similar to a
- :class:`~collections.namedtuple` of the form `(firstiter, finalizer)`,
+ :class:`~collections.namedtuple` of the form ``(firstiter, finalizer)``,
where *firstiter* and *finalizer* are expected to be either ``None`` or
functions which take an :term:`asynchronous generator iterator` as an
argument, and are used to schedule finalization of an asynchronous
diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst
index 054efa81266326..f9a207bad6903f 100644
--- a/Doc/library/unittest.mock-examples.rst
+++ b/Doc/library/unittest.mock-examples.rst
@@ -1116,7 +1116,7 @@ on first use).
That aside there is a way to use ``mock`` to affect the results of an import.
Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it
fetches an *object*, which need not be a module. Importing a module for the
-first time results in a module object being put in `sys.modules`, so usually
+first time results in a module object being put in ``sys.modules``, so usually
when you import something you get a module back. This need not be the case
however.
diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst
index 82e5d6aea2310e..72a7a98c2ac4f2 100644
--- a/Doc/library/xml.dom.minidom.rst
+++ b/Doc/library/xml.dom.minidom.rst
@@ -148,8 +148,8 @@ module documentation. This section lists the differences between the API and
Similarly, explicitly stating the *standalone* argument causes the
standalone document declarations to be added to the prologue of the XML
document.
- If the value is set to `True`, `standalone="yes"` is added,
- otherwise it is set to `"no"`.
+ If the value is set to ``True``, ``standalone="yes"`` is added,
+ otherwise it is set to ``"no"``.
Not stating the argument will omit the declaration from the document.
.. versionchanged:: 3.8
diff --git a/Doc/library/xmlrpc.client.rst b/Doc/library/xmlrpc.client.rst
index 8b09acd4bd3049..bd2c49a6edab7f 100644
--- a/Doc/library/xmlrpc.client.rst
+++ b/Doc/library/xmlrpc.client.rst
@@ -60,7 +60,7 @@ between conformable Python objects and XML on the wire.
may be passed to calls.
The *headers* parameter is an optional sequence of HTTP headers to send with
each request, expressed as a sequence of 2-tuples representing the header
- name and value. (e.g. `[('Header-Name', 'value')]`).
+ name and value. (e.g. ``[('Header-Name', 'value')]``).
The obsolete *use_datetime* flag is similar to *use_builtin_types* but it
applies only to date/time values.
diff --git a/Doc/library/xmlrpc.server.rst b/Doc/library/xmlrpc.server.rst
index 9778a859da1fbf..016369d2b89d2c 100644
--- a/Doc/library/xmlrpc.server.rst
+++ b/Doc/library/xmlrpc.server.rst
@@ -263,7 +263,7 @@ This ExampleService demo can be invoked from the command line::
The client that interacts with the above server is included in
-`Lib/xmlrpc/client.py`::
+``Lib/xmlrpc/client.py``::
server = ServerProxy("http://localhost:8000")
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index a661e03b173498..11f49a8c33dc88 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -1562,7 +1562,7 @@ built-in types.
true).
* Mappings (instances of :class:`dict`) compare equal if and only if they have
- equal `(key, value)` pairs. Equality comparison of the keys and values
+ equal ``(key, value)`` pairs. Equality comparison of the keys and values
enforces reflexivity.
Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
diff --git a/Doc/reference/import.rst b/Doc/reference/import.rst
index b7a53cd0886f29..b22b5251f1de46 100644
--- a/Doc/reference/import.rst
+++ b/Doc/reference/import.rst
@@ -558,6 +558,11 @@ listed below.
It is **strongly** recommended that you rely on :attr:`__spec__`
instead instead of this attribute.
+ .. versionchanged:: 3.12
+ The value of ``__loader__`` is expected to be the same as
+ ``__spec__.loader``. The use of ``__loader__`` is deprecated and slated
+ for removal in Python 3.14.
+
.. attribute:: __package__
The module's ``__package__`` attribute may be set. Its value must
@@ -568,6 +573,9 @@ listed below.
submodules, to the parent package's name. See :pep:`366` for further
details.
+ This attribute is used instead of ``__name__`` to calculate explicit
+ relative imports for main modules, as defined in :pep:`366`.
+
It is **strongly** recommended that you rely on :attr:`__spec__`
instead instead of this attribute.
@@ -822,7 +830,7 @@ The path based finder iterates over every entry in the search path, and
for each of these, looks for an appropriate :term:`path entry finder`
(:class:`~importlib.abc.PathEntryFinder`) for the
path entry. Because this can be an expensive operation (e.g. there may be
-`stat()` call overheads for this search), the path based finder maintains
+``stat()`` call overheads for this search), the path based finder maintains
a cache mapping path entries to path entry finders. This cache is maintained
in :data:`sys.path_importer_cache` (despite the name, this cache actually
stores finder objects rather than being limited to :term:`importer` objects).
diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst
index 8311de0457f6af..5c9937fb5b6d72 100644
--- a/Doc/reference/simple_stmts.rst
+++ b/Doc/reference/simple_stmts.rst
@@ -994,20 +994,12 @@ The :keyword:`!nonlocal` statement
.. productionlist:: python-grammar
nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
-.. XXX add when implemented
- : ["=" (`target_list` "=")+ starred_expression]
- : | "nonlocal" identifier augop expression_list
-
The :keyword:`nonlocal` statement causes the listed identifiers to refer to
previously bound variables in the nearest enclosing scope excluding globals.
This is important because the default behavior for binding is to search the
local namespace first. The statement allows encapsulated code to rebind
variables outside of the local scope besides the global (module) scope.
-.. XXX not implemented
- The :keyword:`nonlocal` statement may prepend an assignment or augmented
- assignment, but not an expression.
-
Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
:keyword:`global` statement, must refer to pre-existing bindings in an
enclosing scope (the scope in which a new binding should be created cannot
diff --git a/Doc/requirements.txt b/Doc/requirements.txt
index 960ac54d7b91ef..7f82dc32113a9d 100644
--- a/Doc/requirements.txt
+++ b/Doc/requirements.txt
@@ -10,7 +10,7 @@ blurb
# sphinx-lint 0.6.2 yields many default role errors due to the new regular
# expression used for default role detection, so we don't use the version
# until the errors are fixed.
-sphinx-lint==0.6.1
+sphinx-lint==0.6.4
# The theme used by the documentation is stored separately, so we need
# to install that as well.
diff --git a/Doc/using/configure.rst b/Doc/using/configure.rst
index ec57c880ee7ad0..b99d9bdaa3f007 100644
--- a/Doc/using/configure.rst
+++ b/Doc/using/configure.rst
@@ -755,12 +755,12 @@ Compiler flags
In particular, :envvar:`CFLAGS` should not contain:
- * the compiler flag `-I` (for setting the search path for include files).
- The `-I` flags are processed from left to right, and any flags in
- :envvar:`CFLAGS` would take precedence over user- and package-supplied `-I`
+ * the compiler flag ``-I`` (for setting the search path for include files).
+ The ``-I`` flags are processed from left to right, and any flags in
+ :envvar:`CFLAGS` would take precedence over user- and package-supplied ``-I``
flags.
- * hardening flags such as `-Werror` because distributions cannot control
+ * hardening flags such as ``-Werror`` because distributions cannot control
whether packages installed by users conform to such heightened
standards.
@@ -878,9 +878,9 @@ Linker flags
In particular, :envvar:`LDFLAGS` should not contain:
- * the compiler flag `-L` (for setting the search path for libraries).
- The `-L` flags are processed from left to right, and any flags in
- :envvar:`LDFLAGS` would take precedence over user- and package-supplied `-L`
+ * the compiler flag ``-L`` (for setting the search path for libraries).
+ The ``-L`` flags are processed from left to right, and any flags in
+ :envvar:`LDFLAGS` would take precedence over user- and package-supplied ``-L``
flags.
.. envvar:: CONFIGURE_LDFLAGS_NODIST
diff --git a/Doc/using/unix.rst b/Doc/using/unix.rst
index 3f9f1364c8ae87..24c02c99f871d5 100644
--- a/Doc/using/unix.rst
+++ b/Doc/using/unix.rst
@@ -158,19 +158,19 @@ Custom OpenSSL
.. code-block:: shell-session
$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz
- $ tar xzf openssl-VERSION
- $ pushd openssl-VERSION
- $ ./config \
- --prefix=/usr/local/custom-openssl \
- --libdir=lib \
- --openssldir=/etc/ssl
- $ make -j1 depend
- $ make -j8
- $ make install_sw
- $ popd
+ $ tar xzf openssl-VERSION
+ $ pushd openssl-VERSION
+ $ ./config \
+ --prefix=/usr/local/custom-openssl \
+ --libdir=lib \
+ --openssldir=/etc/ssl
+ $ make -j1 depend
+ $ make -j8
+ $ make install_sw
+ $ popd
3. Build Python with custom OpenSSL
- (see the configure `--with-openssl` and `--with-openssl-rpath` options)
+ (see the configure ``--with-openssl`` and ``--with-openssl-rpath`` options)
.. code-block:: shell-session
diff --git a/Doc/using/windows.rst b/Doc/using/windows.rst
index 9c339521c31151..b5c2c8ca712041 100644
--- a/Doc/using/windows.rst
+++ b/Doc/using/windows.rst
@@ -216,7 +216,7 @@ of available options is shown below.
+---------------------------+--------------------------------------+--------------------------+
| Include_pip | Install bundled pip and setuptools | 1 |
+---------------------------+--------------------------------------+--------------------------+
-| Include_symbols | Install debugging symbols (`*`.pdb) | 0 |
+| Include_symbols | Install debugging symbols (``*.pdb``)| 0 |
+---------------------------+--------------------------------------+--------------------------+
| Include_tcltk | Install Tcl/Tk support and IDLE | 1 |
+---------------------------+--------------------------------------+--------------------------+
diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst
index 731ce6aac6919d..34f2656f765c7d 100644
--- a/Doc/whatsnew/2.6.rst
+++ b/Doc/whatsnew/2.6.rst
@@ -717,13 +717,13 @@ This will produce the output::
PEP 3101: Advanced String Formatting
=====================================================
-In Python 3.0, the `%` operator is supplemented by a more powerful string
+In Python 3.0, the ``%`` operator is supplemented by a more powerful string
formatting method, :meth:`format`. Support for the :meth:`str.format` method
has been backported to Python 2.6.
-In 2.6, both 8-bit and Unicode strings have a `.format()` method that
+In 2.6, both 8-bit and Unicode strings have a ``.format()`` method that
treats the string as a template and takes the arguments to be formatted.
-The formatting template uses curly brackets (`{`, `}`) as special characters::
+The formatting template uses curly brackets (``{``, ``}``) as special characters::
>>> # Substitute positional argument 0 into the string.
>>> "User ID: {0}".format("root")
diff --git a/Doc/whatsnew/2.7.rst b/Doc/whatsnew/2.7.rst
index e8f701d254cd28..276ab63b97f8a9 100644
--- a/Doc/whatsnew/2.7.rst
+++ b/Doc/whatsnew/2.7.rst
@@ -2485,8 +2485,8 @@ In the standard library:
* The ElementTree library, :mod:`xml.etree`, no longer escapes
ampersands and angle brackets when outputting an XML processing
- instruction (which looks like ``)
- or comment (which looks like ``).
+ instruction (which looks like ````)
+ or comment (which looks like ````).
(Patch by Neil Muller; :issue:`2746`.)
* The :meth:`~StringIO.StringIO.readline` method of :class:`~StringIO.StringIO` objects now does
diff --git a/Doc/whatsnew/3.10.rst b/Doc/whatsnew/3.10.rst
index 428a19453db522..8beb8b19463f82 100644
--- a/Doc/whatsnew/3.10.rst
+++ b/Doc/whatsnew/3.10.rst
@@ -1184,7 +1184,7 @@ and will be incorrect in some rare cases, including some ``_``-s in
New in 3.10 maintenance releases.
-Apply syntax highlighting to `.pyi` files. (Contributed by Alex
+Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
Waygood and Terry Jan Reedy in :issue:`45447`.)
Include prompts when saving Shell with inputs and outputs.
diff --git a/Doc/whatsnew/3.11.rst b/Doc/whatsnew/3.11.rst
index 6103da76a34d03..56a35f4e4802ba 100644
--- a/Doc/whatsnew/3.11.rst
+++ b/Doc/whatsnew/3.11.rst
@@ -723,7 +723,7 @@ hashlib
IDLE and idlelib
----------------
-* Apply syntax highlighting to `.pyi` files. (Contributed by Alex
+* Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
Waygood and Terry Jan Reedy in :issue:`45447`.)
* Include prompts when saving Shell with inputs and outputs.
diff --git a/Doc/whatsnew/3.12.rst b/Doc/whatsnew/3.12.rst
index d18c31fbe9866e..405de11e716b44 100644
--- a/Doc/whatsnew/3.12.rst
+++ b/Doc/whatsnew/3.12.rst
@@ -588,7 +588,7 @@ Porting to Python 3.12
``tp_weaklistoffset``, respectively.
The use of ``tp_dictoffset`` and ``tp_weaklistoffset`` is still
supported, but does not fully support multiple inheritance
- (:gh: `95589`), and performance may be worse.
+ (:gh:`95589`), and performance may be worse.
Classes declaring :const:`Py_TPFLAGS_MANAGED_DICT` should call
:c:func:`_PyObject_VisitManagedDict` and :c:func:`_PyObject_ClearManagedDict`
to traverse and clear their instance's dictionaries.
diff --git a/Doc/whatsnew/3.2.rst b/Doc/whatsnew/3.2.rst
index 65100b0be36a5a..6037db9f954d26 100644
--- a/Doc/whatsnew/3.2.rst
+++ b/Doc/whatsnew/3.2.rst
@@ -1746,7 +1746,7 @@ names.
instead of module names for running specific tests (:issue:`10620`). The new
test discovery can find tests within packages, locating any test importable
from the top-level directory. The top-level directory can be specified with
- the `-t` option, a pattern for matching files with ``-p``, and a directory to
+ the ``-t`` option, a pattern for matching files with ``-p``, and a directory to
start discovery with ``-s``:
.. code-block:: shell-session
@@ -1857,7 +1857,7 @@ asyncore
:class:`asyncore.dispatcher` now provides a
:meth:`~asyncore.dispatcher.handle_accepted()` method
-returning a `(sock, addr)` pair which is called when a connection has actually
+returning a ``(sock, addr)`` pair which is called when a connection has actually
been established with a new remote endpoint. This is supposed to be used as a
replacement for old :meth:`~asyncore.dispatcher.handle_accept()` and avoids
the user to call :meth:`~asyncore.dispatcher.accept()` directly.
diff --git a/Doc/whatsnew/3.3.rst b/Doc/whatsnew/3.3.rst
index fef1a8ac4c0101..96a632577b2c56 100644
--- a/Doc/whatsnew/3.3.rst
+++ b/Doc/whatsnew/3.3.rst
@@ -2389,10 +2389,10 @@ Porting Python code
:attr:`sys.path_importer_cache` where it represents the use of implicit
finders, but semantically it should not change anything.
-* :class:`importlib.abc.Finder` no longer specifies a `find_module()` abstract
+* :class:`importlib.abc.Finder` no longer specifies a ``find_module()`` abstract
method that must be implemented. If you were relying on subclasses to
implement that method, make sure to check for the method's existence first.
- You will probably want to check for `find_loader()` first, though, in the
+ You will probably want to check for ``find_loader()`` first, though, in the
case of working with :term:`path entry finders `.
* :mod:`pkgutil` has been converted to use :mod:`importlib` internally. This
diff --git a/Doc/whatsnew/3.5.rst b/Doc/whatsnew/3.5.rst
index 2c83c7ba3ad3b0..f872579ef546f5 100644
--- a/Doc/whatsnew/3.5.rst
+++ b/Doc/whatsnew/3.5.rst
@@ -2469,11 +2469,11 @@ Changes in the Python API
``opt-`` tag in ``.pyc`` file names. The
:func:`importlib.util.cache_from_source` has gained an *optimization*
parameter to help control the ``opt-`` tag. Because of this, the
- *debug_override* parameter of the function is now deprecated. `.pyo` files
+ *debug_override* parameter of the function is now deprecated. ``.pyo`` files
are also no longer supported as a file argument to the Python interpreter and
thus serve no purpose when distributed on their own (i.e. sourceless code
distribution). Due to the fact that the magic number for bytecode has changed
- in Python 3.5, all old `.pyo` files from previous versions of Python are
+ in Python 3.5, all old ``.pyo`` files from previous versions of Python are
invalid regardless of this PEP.
* The :mod:`socket` module now exports the :data:`~socket.CAN_RAW_FD_FRAMES`
diff --git a/Doc/whatsnew/3.6.rst b/Doc/whatsnew/3.6.rst
index dfb56770ae7026..9308d1a76fec7a 100644
--- a/Doc/whatsnew/3.6.rst
+++ b/Doc/whatsnew/3.6.rst
@@ -960,8 +960,8 @@ contextlib
The :class:`contextlib.AbstractContextManager` class has been added to
provide an abstract base class for context managers. It provides a
-sensible default implementation for `__enter__()` which returns
-``self`` and leaves `__exit__()` an abstract method. A matching
+sensible default implementation for ``__enter__()`` which returns
+``self`` and leaves ``__exit__()`` an abstract method. A matching
class has been added to the :mod:`typing` module as
:class:`typing.ContextManager`.
(Contributed by Brett Cannon in :issue:`25609`.)
@@ -1388,7 +1388,7 @@ are treated as punctuation.
site
----
-When specifying paths to add to :attr:`sys.path` in a `.pth` file,
+When specifying paths to add to :attr:`sys.path` in a ``.pth`` file,
you may now specify file paths on top of directories (e.g. zip files).
(Contributed by Wolfgang Langner in :issue:`26587`).
diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst
index f06cf29c713f99..df3b636cb9ec46 100644
--- a/Doc/whatsnew/3.7.rst
+++ b/Doc/whatsnew/3.7.rst
@@ -2497,7 +2497,7 @@ number of other issues). Some known details affected:
* :c:func:`PySys_AddWarnOptionUnicode` is not currently usable by embedding
applications due to the requirement to create a Unicode object prior to
- calling `Py_Initialize`. Use :c:func:`PySys_AddWarnOption` instead.
+ calling ``Py_Initialize``. Use :c:func:`PySys_AddWarnOption` instead.
* warnings filters added by an embedding application with
:c:func:`PySys_AddWarnOption` should now more consistently take precedence
diff --git a/Doc/whatsnew/3.9.rst b/Doc/whatsnew/3.9.rst
index ff01a65772991f..624e71f9254c45 100644
--- a/Doc/whatsnew/3.9.rst
+++ b/Doc/whatsnew/3.9.rst
@@ -500,7 +500,7 @@ Reedy in :issue:`40468`.) Move the indent space setting from the Font tab to
the new Windows tab. (Contributed by Mark Roseman and Terry Jan Reedy in
:issue:`33962`.)
-Apply syntax highlighting to `.pyi` files. (Contributed by Alex
+Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
Waygood and Terry Jan Reedy in :issue:`45447`.)
imaplib
diff --git a/Lib/asyncio/futures.py b/Lib/asyncio/futures.py
index 39776e3c2cce48..3a6b44a0910869 100644
--- a/Lib/asyncio/futures.py
+++ b/Lib/asyncio/futures.py
@@ -8,7 +8,6 @@
import contextvars
import logging
import sys
-import warnings
from types import GenericAlias
from . import base_futures
@@ -151,11 +150,6 @@ def cancel(self, msg=None):
change the future's state to cancelled, schedule the callbacks and
return True.
"""
- if msg is not None:
- warnings.warn("Passing 'msg' argument to Future.cancel() "
- "is deprecated since Python 3.11, and "
- "scheduled for removal in Python 3.14.",
- DeprecationWarning, stacklevel=2)
self.__log_traceback = False
if self._state != _PENDING:
return False
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py
index 8d6dfcd81b7377..571013745aa03a 100644
--- a/Lib/asyncio/tasks.py
+++ b/Lib/asyncio/tasks.py
@@ -210,11 +210,6 @@ def cancel(self, msg=None):
This also increases the task's count of cancellation requests.
"""
- if msg is not None:
- warnings.warn("Passing 'msg' argument to Task.cancel() "
- "is deprecated since Python 3.11, and "
- "scheduled for removal in Python 3.14.",
- DeprecationWarning, stacklevel=2)
self._log_traceback = False
if self.done():
return False
diff --git a/Lib/importlib/__init__.py b/Lib/importlib/__init__.py
index ce61883288aa35..21d9dee652b3df 100644
--- a/Lib/importlib/__init__.py
+++ b/Lib/importlib/__init__.py
@@ -84,13 +84,13 @@ def find_loader(name, path=None):
try:
loader = sys.modules[name].__loader__
if loader is None:
- raise ValueError('{}.__loader__ is None'.format(name))
+ raise ValueError(f'{name}.__loader__ is None')
else:
return loader
except KeyError:
pass
except AttributeError:
- raise ValueError('{}.__loader__ is not set'.format(name)) from None
+ raise ValueError(f'{name}.__loader__ is not set') from None
spec = _bootstrap._find_spec(name, path)
# We won't worry about malformed specs (missing attributes).
@@ -98,8 +98,7 @@ def find_loader(name, path=None):
return None
if spec.loader is None:
if spec.submodule_search_locations is None:
- raise ImportError('spec for {} missing loader'.format(name),
- name=name)
+ raise ImportError(f'spec for {name} missing loader', name=name)
raise ImportError('namespace packages do not have loaders',
name=name)
return spec.loader
@@ -116,9 +115,8 @@ def import_module(name, package=None):
level = 0
if name.startswith('.'):
if not package:
- msg = ("the 'package' argument is required to perform a relative "
- "import for {!r}")
- raise TypeError(msg.format(name))
+ raise TypeError("the 'package' argument is required to perform a "
+ f"relative import for {name!r}")
for character in name:
if character != '.':
break
@@ -144,8 +142,7 @@ def reload(module):
raise TypeError("reload() argument must be a module")
if sys.modules.get(name) is not module:
- msg = "module {} not in sys.modules"
- raise ImportError(msg.format(name), name=name)
+ raise ImportError(f"module {name} not in sys.modules", name=name)
if name in _RELOADING:
return _RELOADING[name]
_RELOADING[name] = module
@@ -155,8 +152,7 @@ def reload(module):
try:
parent = sys.modules[parent_name]
except KeyError:
- msg = "parent {!r} not in sys.modules"
- raise ImportError(msg.format(parent_name),
+ raise ImportError(f"parent {parent_name!r} not in sys.modules",
name=parent_name) from None
else:
pkgpath = parent.__path__
diff --git a/Lib/importlib/_bootstrap_external.py b/Lib/importlib/_bootstrap_external.py
index efda49382540c5..fc50e70539cacf 100644
--- a/Lib/importlib/_bootstrap_external.py
+++ b/Lib/importlib/_bootstrap_external.py
@@ -197,7 +197,7 @@ def _write_atomic(path, data, mode=0o666):
Be prepared to handle a FileExistsError if concurrent writing of the
temporary file is attempted."""
# id() is used to generate a pseudo-random filename.
- path_tmp = '{}.{}'.format(path, id(path))
+ path_tmp = f'{path}.{id(path)}'
fd = _os.open(path_tmp,
_os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
try:
@@ -492,8 +492,8 @@ def cache_from_source(path, debug_override=None, *, optimization=None):
optimization = str(optimization)
if optimization != '':
if not optimization.isalnum():
- raise ValueError('{!r} is not alphanumeric'.format(optimization))
- almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization)
+ raise ValueError(f'{optimization!r} is not alphanumeric')
+ almost_filename = f'{almost_filename}.{_OPT}{optimization}'
filename = almost_filename + BYTECODE_SUFFIXES[0]
if sys.pycache_prefix is not None:
# We need an absolute path to the py file to avoid the possibility of
@@ -651,8 +651,8 @@ def _find_module_shim(self, fullname):
# return None.
loader, portions = self.find_loader(fullname)
if loader is None and len(portions):
- msg = 'Not importing directory {}: missing __init__'
- _warnings.warn(msg.format(portions[0]), ImportWarning)
+ msg = f'Not importing directory {portions[0]}: missing __init__'
+ _warnings.warn(msg, ImportWarning)
return loader
@@ -750,7 +750,7 @@ def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
_imp._fix_co_filename(code, source_path)
return code
else:
- raise ImportError('Non-code object in {!r}'.format(bytecode_path),
+ raise ImportError(f'Non-code object in {bytecode_path!r}',
name=name, path=bytecode_path)
@@ -862,6 +862,54 @@ def spec_from_file_location(name, location=None, *, loader=None,
return spec
+def _bless_my_loader(module_globals):
+ """Helper function for _warnings.c
+
+ See GH#97850 for details.
+ """
+ # 2022-10-06(warsaw): For now, this helper is only used in _warnings.c and
+ # that use case only has the module globals. This function could be
+ # extended to accept either that or a module object. However, in the
+ # latter case, it would be better to raise certain exceptions when looking
+ # at a module, which should have either a __loader__ or __spec__.loader.
+ # For backward compatibility, it is possible that we'll get an empty
+ # dictionary for the module globals, and that cannot raise an exception.
+ if not isinstance(module_globals, dict):
+ return None
+
+ missing = object()
+ loader = module_globals.get('__loader__', None)
+ spec = module_globals.get('__spec__', missing)
+
+ if loader is None:
+ if spec is missing:
+ # If working with a module:
+ # raise AttributeError('Module globals is missing a __spec__')
+ return None
+ elif spec is None:
+ raise ValueError('Module globals is missing a __spec__.loader')
+
+ spec_loader = getattr(spec, 'loader', missing)
+
+ if spec_loader in (missing, None):
+ if loader is None:
+ exc = AttributeError if spec_loader is missing else ValueError
+ raise exc('Module globals is missing a __spec__.loader')
+ _warnings.warn(
+ 'Module globals is missing a __spec__.loader',
+ DeprecationWarning)
+ spec_loader = loader
+
+ assert spec_loader is not None
+ if loader is not None and loader != spec_loader:
+ _warnings.warn(
+ 'Module globals; __loader__ != __spec__.loader',
+ DeprecationWarning)
+ return loader
+
+ return spec_loader
+
+
# Loaders #####################################################################
class WindowsRegistryFinder:
@@ -951,8 +999,8 @@ def exec_module(self, module):
"""Execute the module."""
code = self.get_code(module.__name__)
if code is None:
- raise ImportError('cannot load module {!r} when get_code() '
- 'returns None'.format(module.__name__))
+ raise ImportError(f'cannot load module {module.__name__!r} when '
+ 'get_code() returns None')
_bootstrap._call_with_frames_removed(exec, code, module.__dict__)
def load_module(self, fullname):
@@ -1337,7 +1385,7 @@ def __len__(self):
return len(self._recalculate())
def __repr__(self):
- return '_NamespacePath({!r})'.format(self._path)
+ return f'_NamespacePath({self._path!r})'
def __contains__(self, item):
return item in self._recalculate()
@@ -1678,7 +1726,7 @@ def _fill_cache(self):
for item in contents:
name, dot, suffix = item.partition('.')
if dot:
- new_name = '{}.{}'.format(name, suffix.lower())
+ new_name = f'{name}.{suffix.lower()}'
else:
new_name = name
lower_suffix_contents.add(new_name)
@@ -1705,7 +1753,7 @@ def path_hook_for_FileFinder(path):
return path_hook_for_FileFinder
def __repr__(self):
- return 'FileFinder({!r})'.format(self.path)
+ return f'FileFinder({self.path!r})'
# Import setup ###############################################################
diff --git a/Lib/importlib/resources/_adapters.py b/Lib/importlib/resources/_adapters.py
index ea363d86a564b5..f22f6bc509a3d7 100644
--- a/Lib/importlib/resources/_adapters.py
+++ b/Lib/importlib/resources/_adapters.py
@@ -35,7 +35,7 @@ def _io_wrapper(file, mode='r', *args, **kwargs):
elif mode == 'rb':
return file
raise ValueError(
- "Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode)
+ f"Invalid mode value '{mode}', only 'r' and 'rb' are supported"
)
diff --git a/Lib/importlib/util.py b/Lib/importlib/util.py
index 7f15b029b24050..5294578cc26cf3 100644
--- a/Lib/importlib/util.py
+++ b/Lib/importlib/util.py
@@ -11,12 +11,9 @@
from ._bootstrap_external import source_from_cache
from ._bootstrap_external import spec_from_file_location
-from contextlib import contextmanager
import _imp
-import functools
import sys
import types
-import warnings
def source_hash(source_bytes):
@@ -63,10 +60,10 @@ def _find_spec_from_path(name, path=None):
try:
spec = module.__spec__
except AttributeError:
- raise ValueError('{}.__spec__ is not set'.format(name)) from None
+ raise ValueError(f'{name}.__spec__ is not set') from None
else:
if spec is None:
- raise ValueError('{}.__spec__ is None'.format(name))
+ raise ValueError(f'{name}.__spec__ is None')
return spec
@@ -108,97 +105,13 @@ def find_spec(name, package=None):
try:
spec = module.__spec__
except AttributeError:
- raise ValueError('{}.__spec__ is not set'.format(name)) from None
+ raise ValueError(f'{name}.__spec__ is not set') from None
else:
if spec is None:
- raise ValueError('{}.__spec__ is None'.format(name))
+ raise ValueError(f'{name}.__spec__ is None')
return spec
-@contextmanager
-def _module_to_load(name):
- is_reload = name in sys.modules
-
- module = sys.modules.get(name)
- if not is_reload:
- # This must be done before open() is called as the 'io' module
- # implicitly imports 'locale' and would otherwise trigger an
- # infinite loop.
- module = type(sys)(name)
- # This must be done before putting the module in sys.modules
- # (otherwise an optimization shortcut in import.c becomes wrong)
- module.__initializing__ = True
- sys.modules[name] = module
- try:
- yield module
- except Exception:
- if not is_reload:
- try:
- del sys.modules[name]
- except KeyError:
- pass
- finally:
- module.__initializing__ = False
-
-
-def set_loader(fxn):
- """Set __loader__ on the returned module.
-
- This function is deprecated.
-
- """
- @functools.wraps(fxn)
- def set_loader_wrapper(self, *args, **kwargs):
- warnings.warn('The import system now takes care of this automatically; '
- 'this decorator is slated for removal in Python 3.12',
- DeprecationWarning, stacklevel=2)
- module = fxn(self, *args, **kwargs)
- if getattr(module, '__loader__', None) is None:
- module.__loader__ = self
- return module
- return set_loader_wrapper
-
-
-def module_for_loader(fxn):
- """Decorator to handle selecting the proper module for loaders.
-
- The decorated function is passed the module to use instead of the module
- name. The module passed in to the function is either from sys.modules if
- it already exists or is a new module. If the module is new, then __name__
- is set the first argument to the method, __loader__ is set to self, and
- __package__ is set accordingly (if self.is_package() is defined) will be set
- before it is passed to the decorated function (if self.is_package() does
- not work for the module it will be set post-load).
-
- If an exception is raised and the decorator created the module it is
- subsequently removed from sys.modules.
-
- The decorator assumes that the decorated function takes the module name as
- the second argument.
-
- """
- warnings.warn('The import system now takes care of this automatically; '
- 'this decorator is slated for removal in Python 3.12',
- DeprecationWarning, stacklevel=2)
- @functools.wraps(fxn)
- def module_for_loader_wrapper(self, fullname, *args, **kwargs):
- with _module_to_load(fullname) as module:
- module.__loader__ = self
- try:
- is_package = self.is_package(fullname)
- except (ImportError, AttributeError):
- pass
- else:
- if is_package:
- module.__package__ = fullname
- else:
- module.__package__ = fullname.rpartition('.')[0]
- # If __package__ was not set above, __import__() will do it later.
- return fxn(self, module, *args, **kwargs)
-
- return module_for_loader_wrapper
-
-
class _LazyModule(types.ModuleType):
"""A subclass of the module type which triggers loading upon attribute access."""
diff --git a/Lib/test/test_asyncio/test_futures.py b/Lib/test/test_asyncio/test_futures.py
index 3dc6b658cfae8d..83ea01c2452521 100644
--- a/Lib/test/test_asyncio/test_futures.py
+++ b/Lib/test/test_asyncio/test_futures.py
@@ -229,22 +229,14 @@ def test_future_cancel_message_getter(self):
self.assertTrue(hasattr(f, '_cancel_message'))
self.assertEqual(f._cancel_message, None)
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- f.cancel('my message')
+ f.cancel('my message')
with self.assertRaises(asyncio.CancelledError):
self.loop.run_until_complete(f)
self.assertEqual(f._cancel_message, 'my message')
def test_future_cancel_message_setter(self):
f = self._new_future(loop=self.loop)
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- f.cancel('my message')
+ f.cancel('my message')
f._cancel_message = 'my new message'
self.assertEqual(f._cancel_message, 'my new message')
diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py
index 2491285206bcd7..0e38e6a92e52b7 100644
--- a/Lib/test/test_asyncio/test_tasks.py
+++ b/Lib/test/test_asyncio/test_tasks.py
@@ -109,11 +109,7 @@ async def coro():
self.assertTrue(hasattr(t, '_cancel_message'))
self.assertEqual(t._cancel_message, None)
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- t.cancel('my message')
+ t.cancel('my message')
self.assertEqual(t._cancel_message, 'my message')
with self.assertRaises(asyncio.CancelledError) as cm:
@@ -125,11 +121,7 @@ def test_task_cancel_message_setter(self):
async def coro():
pass
t = self.new_task(self.loop, coro())
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- t.cancel('my message')
+ t.cancel('my message')
t._cancel_message = 'my new message'
self.assertEqual(t._cancel_message, 'my new message')
@@ -706,14 +698,7 @@ async def sleep():
async def coro():
task = self.new_task(loop, sleep())
await asyncio.sleep(0)
- if cancel_args not in ((), (None,)):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- task.cancel(*cancel_args)
- else:
- task.cancel(*cancel_args)
+ task.cancel(*cancel_args)
done, pending = await asyncio.wait([task])
task.result()
@@ -747,14 +732,7 @@ async def sleep():
async def coro():
task = self.new_task(loop, sleep())
await asyncio.sleep(0)
- if cancel_args not in ((), (None,)):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- task.cancel(*cancel_args)
- else:
- task.cancel(*cancel_args)
+ task.cancel(*cancel_args)
done, pending = await asyncio.wait([task])
task.exception()
@@ -777,17 +755,10 @@ async def sleep():
fut.set_result(None)
await asyncio.sleep(10)
- def cancel(task, msg):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- task.cancel(msg)
-
async def coro():
inner_task = self.new_task(loop, sleep())
await fut
- loop.call_soon(cancel, inner_task, 'msg')
+ loop.call_soon(inner_task.cancel, 'msg')
try:
await inner_task
except asyncio.CancelledError as ex:
@@ -813,11 +784,7 @@ async def sleep():
async def coro():
task = self.new_task(loop, sleep())
# We deliberately leave out the sleep here.
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- task.cancel('my message')
+ task.cancel('my message')
done, pending = await asyncio.wait([task])
task.exception()
@@ -2179,14 +2146,7 @@ async def test():
async def main():
qwe = self.new_task(loop, test())
await asyncio.sleep(0.2)
- if cancel_args not in ((), (None,)):
- with self.assertWarnsRegex(
- DeprecationWarning,
- "Passing 'msg' argument"
- ):
- qwe.cancel(*cancel_args)
- else:
- qwe.cancel(*cancel_args)
+ qwe.cancel(*cancel_args)
await qwe
try:
diff --git a/Lib/test/test_importlib/import_/test_helpers.py b/Lib/test/test_importlib/import_/test_helpers.py
index 90df56f09fe52d..550f88d1d7a651 100644
--- a/Lib/test/test_importlib/import_/test_helpers.py
+++ b/Lib/test/test_importlib/import_/test_helpers.py
@@ -2,7 +2,9 @@
from importlib import _bootstrap_external, machinery
import os.path
+from types import ModuleType, SimpleNamespace
import unittest
+import warnings
from .. import util
@@ -67,5 +69,116 @@ def test_no_loader_no_spec_but_source(self):
FrozenFixUpModuleTests, SourceFixUpModuleTests = util.test_both(FixUpModuleTests)
+
+class TestBlessMyLoader(unittest.TestCase):
+ # GH#86298 is part of the migration away from module attributes and toward
+ # __spec__ attributes. There are several cases to test here. This will
+ # have to change in Python 3.14 when we actually remove/ignore __loader__
+ # in favor of requiring __spec__.loader.
+
+ def test_gh86298_no_loader_and_no_spec(self):
+ bar = ModuleType('bar')
+ del bar.__loader__
+ del bar.__spec__
+ # 2022-10-06(warsaw): For backward compatibility with the
+ # implementation in _warnings.c, this can't raise an
+ # AttributeError. See _bless_my_loader() in _bootstrap_external.py
+ # If working with a module:
+ ## self.assertRaises(
+ ## AttributeError, _bootstrap_external._bless_my_loader,
+ ## bar.__dict__)
+ self.assertIsNone(_bootstrap_external._bless_my_loader(bar.__dict__))
+
+ def test_gh86298_loader_is_none_and_no_spec(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = None
+ del bar.__spec__
+ # 2022-10-06(warsaw): For backward compatibility with the
+ # implementation in _warnings.c, this can't raise an
+ # AttributeError. See _bless_my_loader() in _bootstrap_external.py
+ # If working with a module:
+ ## self.assertRaises(
+ ## AttributeError, _bootstrap_external._bless_my_loader,
+ ## bar.__dict__)
+ self.assertIsNone(_bootstrap_external._bless_my_loader(bar.__dict__))
+
+ def test_gh86298_no_loader_and_spec_is_none(self):
+ bar = ModuleType('bar')
+ del bar.__loader__
+ bar.__spec__ = None
+ self.assertRaises(
+ ValueError,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_loader_is_none_and_spec_is_none(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = None
+ bar.__spec__ = None
+ self.assertRaises(
+ ValueError,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_loader_is_none_and_spec_loader_is_none(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = None
+ bar.__spec__ = SimpleNamespace(loader=None)
+ self.assertRaises(
+ ValueError,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_no_spec(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = object()
+ del bar.__spec__
+ with warnings.catch_warnings():
+ self.assertWarns(
+ DeprecationWarning,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_spec_is_none(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = object()
+ bar.__spec__ = None
+ with warnings.catch_warnings():
+ self.assertWarns(
+ DeprecationWarning,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_no_spec_loader(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = object()
+ bar.__spec__ = SimpleNamespace()
+ with warnings.catch_warnings():
+ self.assertWarns(
+ DeprecationWarning,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_loader_and_spec_loader_disagree(self):
+ bar = ModuleType('bar')
+ bar.__loader__ = object()
+ bar.__spec__ = SimpleNamespace(loader=object())
+ with warnings.catch_warnings():
+ self.assertWarns(
+ DeprecationWarning,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_no_loader_and_no_spec_loader(self):
+ bar = ModuleType('bar')
+ del bar.__loader__
+ bar.__spec__ = SimpleNamespace()
+ self.assertRaises(
+ AttributeError,
+ _bootstrap_external._bless_my_loader, bar.__dict__)
+
+ def test_gh86298_no_loader_with_spec_loader_okay(self):
+ bar = ModuleType('bar')
+ del bar.__loader__
+ loader = object()
+ bar.__spec__ = SimpleNamespace(loader=loader)
+ self.assertEqual(
+ _bootstrap_external._bless_my_loader(bar.__dict__),
+ loader)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/test/test_importlib/test_abc.py b/Lib/test/test_importlib/test_abc.py
index 8641b6cc683052..3c9149c4e45a92 100644
--- a/Lib/test/test_importlib/test_abc.py
+++ b/Lib/test/test_importlib/test_abc.py
@@ -771,13 +771,7 @@ def verify_code(self, code_object):
class SourceOnlyLoaderTests(SourceLoaderTestHarness):
-
- """Test importlib.abc.SourceLoader for source-only loading.
-
- Reload testing is subsumed by the tests for
- importlib.util.module_for_loader.
-
- """
+ """Test importlib.abc.SourceLoader for source-only loading."""
def test_get_source(self):
# Verify the source code is returned as a string.
diff --git a/Lib/test/test_importlib/test_spec.py b/Lib/test/test_importlib/test_spec.py
index f1ab16c7b2a9be..80aa3609c6f96e 100644
--- a/Lib/test/test_importlib/test_spec.py
+++ b/Lib/test/test_importlib/test_spec.py
@@ -47,21 +47,6 @@ def exec_module(self, module):
module.eggs = self.EGGS
-class LegacyLoader(TestLoader):
-
- HAM = -1
-
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
-
- frozen_util = util['Frozen']
-
- @frozen_util.module_for_loader
- def load_module(self, module):
- module.ham = self.HAM
- return module
-
-
class ModuleSpecTests:
def setUp(self):
@@ -302,26 +287,6 @@ def exec_module(self, module):
loaded = self.bootstrap._load(self.spec)
self.assertNotIn(self.spec.name, sys.modules)
- def test_load_legacy(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", ImportWarning)
- self.spec.loader = LegacyLoader()
- with CleanImport(self.spec.name):
- loaded = self.bootstrap._load(self.spec)
-
- self.assertEqual(loaded.ham, -1)
-
- def test_load_legacy_attributes(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", ImportWarning)
- self.spec.loader = LegacyLoader()
- with CleanImport(self.spec.name):
- loaded = self.bootstrap._load(self.spec)
-
- self.assertIs(loaded.__loader__, self.spec.loader)
- self.assertEqual(loaded.__package__, self.spec.parent)
- self.assertIs(loaded.__spec__, self.spec)
-
def test_load_legacy_attributes_immutable(self):
module = object()
with warnings.catch_warnings():
@@ -387,19 +352,6 @@ def test_reload_init_module_attrs(self):
self.assertFalse(hasattr(loaded, '__file__'))
self.assertFalse(hasattr(loaded, '__cached__'))
- def test_reload_legacy(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", ImportWarning)
- self.spec.loader = LegacyLoader()
- with CleanImport(self.spec.name):
- loaded = self.bootstrap._load(self.spec)
- reloaded = self.bootstrap._exec(self.spec, loaded)
- installed = sys.modules[self.spec.name]
-
- self.assertEqual(loaded.ham, -1)
- self.assertIs(reloaded, loaded)
- self.assertIs(installed, loaded)
-
(Frozen_ModuleSpecMethodsTests,
Source_ModuleSpecMethodsTests
diff --git a/Lib/test/test_importlib/test_util.py b/Lib/test/test_importlib/test_util.py
index e70971e9d3bc84..08a615ecf5288b 100644
--- a/Lib/test/test_importlib/test_util.py
+++ b/Lib/test/test_importlib/test_util.py
@@ -121,184 +121,6 @@ def test___cached__(self):
util=importlib_util)
-class ModuleForLoaderTests:
-
- """Tests for importlib.util.module_for_loader."""
-
- @classmethod
- def module_for_loader(cls, func):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- return cls.util.module_for_loader(func)
-
- def test_warning(self):
- # Should raise a PendingDeprecationWarning when used.
- with warnings.catch_warnings():
- warnings.simplefilter('error', DeprecationWarning)
- with self.assertRaises(DeprecationWarning):
- func = self.util.module_for_loader(lambda x: x)
-
- def return_module(self, name):
- fxn = self.module_for_loader(lambda self, module: module)
- return fxn(self, name)
-
- def raise_exception(self, name):
- def to_wrap(self, module):
- raise ImportError
- fxn = self.module_for_loader(to_wrap)
- try:
- fxn(self, name)
- except ImportError:
- pass
-
- def test_new_module(self):
- # Test that when no module exists in sys.modules a new module is
- # created.
- module_name = 'a.b.c'
- with util.uncache(module_name):
- module = self.return_module(module_name)
- self.assertIn(module_name, sys.modules)
- self.assertIsInstance(module, types.ModuleType)
- self.assertEqual(module.__name__, module_name)
-
- def test_reload(self):
- # Test that a module is reused if already in sys.modules.
- class FakeLoader:
- def is_package(self, name):
- return True
- @self.module_for_loader
- def load_module(self, module):
- return module
- name = 'a.b.c'
- module = types.ModuleType('a.b.c')
- module.__loader__ = 42
- module.__package__ = 42
- with util.uncache(name):
- sys.modules[name] = module
- loader = FakeLoader()
- returned_module = loader.load_module(name)
- self.assertIs(returned_module, sys.modules[name])
- self.assertEqual(module.__loader__, loader)
- self.assertEqual(module.__package__, name)
-
- def test_new_module_failure(self):
- # Test that a module is removed from sys.modules if added but an
- # exception is raised.
- name = 'a.b.c'
- with util.uncache(name):
- self.raise_exception(name)
- self.assertNotIn(name, sys.modules)
-
- def test_reload_failure(self):
- # Test that a failure on reload leaves the module in-place.
- name = 'a.b.c'
- module = types.ModuleType(name)
- with util.uncache(name):
- sys.modules[name] = module
- self.raise_exception(name)
- self.assertIs(module, sys.modules[name])
-
- def test_decorator_attrs(self):
- def fxn(self, module): pass
- wrapped = self.module_for_loader(fxn)
- self.assertEqual(wrapped.__name__, fxn.__name__)
- self.assertEqual(wrapped.__qualname__, fxn.__qualname__)
-
- def test_false_module(self):
- # If for some odd reason a module is considered false, still return it
- # from sys.modules.
- class FalseModule(types.ModuleType):
- def __bool__(self): return False
-
- name = 'mod'
- module = FalseModule(name)
- with util.uncache(name):
- self.assertFalse(module)
- sys.modules[name] = module
- given = self.return_module(name)
- self.assertIs(given, module)
-
- def test_attributes_set(self):
- # __name__, __loader__, and __package__ should be set (when
- # is_package() is defined; undefined implicitly tested elsewhere).
- class FakeLoader:
- def __init__(self, is_package):
- self._pkg = is_package
- def is_package(self, name):
- return self._pkg
- @self.module_for_loader
- def load_module(self, module):
- return module
-
- name = 'pkg.mod'
- with util.uncache(name):
- loader = FakeLoader(False)
- module = loader.load_module(name)
- self.assertEqual(module.__name__, name)
- self.assertIs(module.__loader__, loader)
- self.assertEqual(module.__package__, 'pkg')
-
- name = 'pkg.sub'
- with util.uncache(name):
- loader = FakeLoader(True)
- module = loader.load_module(name)
- self.assertEqual(module.__name__, name)
- self.assertIs(module.__loader__, loader)
- self.assertEqual(module.__package__, name)
-
-
-(Frozen_ModuleForLoaderTests,
- Source_ModuleForLoaderTests
- ) = util.test_both(ModuleForLoaderTests, util=importlib_util)
-
-
-class SetLoaderTests:
-
- """Tests importlib.util.set_loader()."""
-
- @property
- def DummyLoader(self):
- # Set DummyLoader on the class lazily.
- class DummyLoader:
- @self.util.set_loader
- def load_module(self, module):
- return self.module
- self.__class__.DummyLoader = DummyLoader
- return DummyLoader
-
- def test_no_attribute(self):
- loader = self.DummyLoader()
- loader.module = types.ModuleType('blah')
- try:
- del loader.module.__loader__
- except AttributeError:
- pass
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- self.assertEqual(loader, loader.load_module('blah').__loader__)
-
- def test_attribute_is_None(self):
- loader = self.DummyLoader()
- loader.module = types.ModuleType('blah')
- loader.module.__loader__ = None
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- self.assertEqual(loader, loader.load_module('blah').__loader__)
-
- def test_not_reset(self):
- loader = self.DummyLoader()
- loader.module = types.ModuleType('blah')
- loader.module.__loader__ = 42
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', DeprecationWarning)
- self.assertEqual(42, loader.load_module('blah').__loader__)
-
-
-(Frozen_SetLoaderTests,
- Source_SetLoaderTests
- ) = util.test_both(SetLoaderTests, util=importlib_util)
-
-
class ResolveNameTests:
"""Tests importlib.util.resolve_name()."""
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-10-01-08-55-09.gh-issue-97591.pw6kkH.rst b/Misc/NEWS.d/next/Core and Builtins/2022-10-01-08-55-09.gh-issue-97591.pw6kkH.rst
index d3a5867db7fce2..6f07529f15bba3 100644
--- a/Misc/NEWS.d/next/Core and Builtins/2022-10-01-08-55-09.gh-issue-97591.pw6kkH.rst
+++ b/Misc/NEWS.d/next/Core and Builtins/2022-10-01-08-55-09.gh-issue-97591.pw6kkH.rst
@@ -1,2 +1,2 @@
-Fixed a missing incref/decref pair in `Exception.__setstate__()`.
+Fixed a missing incref/decref pair in ``Exception.__setstate__()``.
Patch by Ofey Chan.
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-10-04-14-04-40.gh-issue-86298.QVM7G1.rst b/Misc/NEWS.d/next/Core and Builtins/2022-10-04-14-04-40.gh-issue-86298.QVM7G1.rst
new file mode 100644
index 00000000000000..6e349d56c99f25
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2022-10-04-14-04-40.gh-issue-86298.QVM7G1.rst
@@ -0,0 +1,3 @@
+In cases where ``warnings.warn_explicit()`` consults the module's loader, an
+``DeprecationWarning`` is issued when ``m.__loader__`` differs from
+``m.__spec__.loader``.
diff --git a/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst b/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst
index a5858f432932ca..c4d296e626b1b5 100644
--- a/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst
+++ b/Misc/NEWS.d/next/Documentation/2022-09-01-17-03-04.gh-issue-96432.1EJ1-4.rst
@@ -1,2 +1,2 @@
Fraction literals now support whitespace around the forward slash,
-`Fraction('2 / 3')`.
+``Fraction('2 / 3')``.
diff --git a/Misc/NEWS.d/next/Library/2019-11-04-22-21-27.bpo-38693.w_OAov.rst b/Misc/NEWS.d/next/Library/2019-11-04-22-21-27.bpo-38693.w_OAov.rst
index 6d0ad36809ee77..a81e9220a8e6d3 100644
--- a/Misc/NEWS.d/next/Library/2019-11-04-22-21-27.bpo-38693.w_OAov.rst
+++ b/Misc/NEWS.d/next/Library/2019-11-04-22-21-27.bpo-38693.w_OAov.rst
@@ -1 +1 @@
-importlib now uses f-strings internally instead of str.format().
+:mod:`importlib` now uses f-strings internally instead of ``str.format``.
diff --git a/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst b/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst
index ba69a011601fd0..16bad6d34b1c0b 100644
--- a/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst
+++ b/Misc/NEWS.d/next/Library/2022-05-09-21-31-41.gh-issue-92445.tJosdm.rst
@@ -1,3 +1,3 @@
-Fix a bug in :mod:`argparse` where `nargs="*"` would raise an error instead of returning
+Fix a bug in :mod:`argparse` where ``nargs="*"`` would raise an error instead of returning
an empty list when 0 arguments were supplied if choice was also defined in
``parser.add_argument``.
diff --git a/Misc/NEWS.d/next/Library/2022-07-06-14-57-33.gh-issue-94619.PRqKVX.rst b/Misc/NEWS.d/next/Library/2022-07-06-14-57-33.gh-issue-94619.PRqKVX.rst
index a7905034424684..987ea6b045afda 100644
--- a/Misc/NEWS.d/next/Library/2022-07-06-14-57-33.gh-issue-94619.PRqKVX.rst
+++ b/Misc/NEWS.d/next/Library/2022-07-06-14-57-33.gh-issue-94619.PRqKVX.rst
@@ -1 +1 @@
-Remove the long-deprecated `module_repr()` from `importlib`.
+Remove the long-deprecated ``module_repr()`` from :mod:`importlib`.
diff --git a/Misc/NEWS.d/next/Library/2022-10-05-11-40-02.gh-issue-97850.NzdREm.rst b/Misc/NEWS.d/next/Library/2022-10-05-11-40-02.gh-issue-97850.NzdREm.rst
new file mode 100644
index 00000000000000..5e759bc0995a04
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-10-05-11-40-02.gh-issue-97850.NzdREm.rst
@@ -0,0 +1,2 @@
+Remove deprecated :func:`importlib.utils.set_loader` and
+:func:`importlib.utils.module_for_loader` from :mod:`importlib.utils`.
diff --git a/Misc/NEWS.d/next/Library/2022-10-06-23-42-00.gh-issue-90985.s280JY.rst b/Misc/NEWS.d/next/Library/2022-10-06-23-42-00.gh-issue-90985.s280JY.rst
new file mode 100644
index 00000000000000..964aa3986331a2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-10-06-23-42-00.gh-issue-90985.s280JY.rst
@@ -0,0 +1 @@
+Earlier in 3.11 we deprecated ``asyncio.Task.cancel("message")``. We realized we were too harsh, and have undeprecated it.
diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c
index efa0d2d6906eab..ab6219c322f9fd 100644
--- a/Modules/_asynciomodule.c
+++ b/Modules/_asynciomodule.c
@@ -1116,16 +1116,6 @@ static PyObject *
_asyncio_Future_cancel_impl(FutureObj *self, PyObject *msg)
/*[clinic end generated code: output=3edebbc668e5aba3 input=925eb545251f2c5a]*/
{
- if (msg != Py_None) {
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "Passing 'msg' argument to Future.cancel() "
- "is deprecated since Python 3.11, and "
- "scheduled for removal in Python 3.14.",
- 2))
- {
- return NULL;
- }
- }
ENSURE_FUTURE_ALIVE(self)
return future_cancel(self, msg);
}
@@ -2214,16 +2204,6 @@ static PyObject *
_asyncio_Task_cancel_impl(TaskObj *self, PyObject *msg)
/*[clinic end generated code: output=c66b60d41c74f9f1 input=7bb51bf25974c783]*/
{
- if (msg != Py_None) {
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "Passing 'msg' argument to Task.cancel() "
- "is deprecated since Python 3.11, and "
- "scheduled for removal in Python 3.14.",
- 2))
- {
- return NULL;
- }
- }
self->task_log_tb = 0;
if (self->task_state != STATE_PENDING) {
diff --git a/Python/_warnings.c b/Python/_warnings.c
index 1b9e107ea30b13..0d4c50f769b03c 100644
--- a/Python/_warnings.c
+++ b/Python/_warnings.c
@@ -977,6 +977,7 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
static PyObject *
get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno)
{
+ PyObject *external;
PyObject *loader;
PyObject *module_name;
PyObject *get_source;
@@ -984,12 +985,18 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
PyObject *source_list;
PyObject *source_line;
- /* Check/get the requisite pieces needed for the loader. */
- loader = _PyDict_GetItemWithError(module_globals, &_Py_ID(__loader__));
+ /* stolen from import.c */
+ external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
+ if (external == NULL) {
+ return NULL;
+ }
+
+ loader = PyObject_CallMethod(external, "_bless_my_loader", "O", module_globals, NULL);
+ Py_DECREF(external);
if (loader == NULL) {
return NULL;
}
- Py_INCREF(loader);
+
module_name = _PyDict_GetItemWithError(module_globals, &_Py_ID(__name__));
if (!module_name) {
Py_DECREF(loader);