mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() (GH-97803)
In `_warnings.c`, in the C equivalent of `warnings.warn_explicit()`, if the module globals are given (and not None), the warning will attempt to get the source line for the issued warning. To do this, it needs the module's loader. Previously, it would only look up `__loader__` in the module globals. In https://github.com/python/cpython/issues/86298 we want to defer to the `__spec__.loader` if available. The first step on this journey is to check that `loader == __spec__.loader` and issue another warning if it is not. This commit does that. Since this is a PoC, only manual testing for now. ```python # /tmp/foo.py import warnings import bar warnings.warn_explicit( 'warning!', RuntimeWarning, 'bar.py', 2, module='bar knee', module_globals=bar.__dict__, ) ``` ```python # /tmp/bar.py import sys import os import pathlib # __loader__ = pathlib.Path() ``` Then running this: `./python.exe -Wdefault /tmp/foo.py` Produces: ``` bar.py:2: RuntimeWarning: warning! import os ``` Uncomment the `__loader__ = ` line in `bar.py` and try it again: ``` sys:1: ImportWarning: Module bar; __loader__ != __spec__.loader (<_frozen_importlib_external.SourceFileLoader object at 0x109f7dfa0> != PosixPath('.')) bar.py:2: RuntimeWarning: warning! import os ``` Automerge-Triggered-By: GH:warsaw
This commit is contained in:
parent
27369ef56f
commit
13d4489142
5 changed files with 182 additions and 3 deletions
|
@ -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.
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue