Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() #97803

Merged
merged 17 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Doc/reference/import.rst
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,11 @@ the module.
for introspection, but can be used for additional loader-specific
functionality, for example getting data associated with a loader.

.. versionchanged:: 3.12
The value of ``__loader__`` is expected to be the same as
``__spec__.loader``. If they are not, an :exc:`ImportWarning` will be
raised.

.. attribute:: __package__

The module's ``__package__`` attribute must be set. Its value must
Expand All @@ -563,8 +568,7 @@ the module.
details.

This attribute is used instead of ``__name__`` to calculate explicit
relative imports for main modules, as defined in :pep:`366`. It is
expected to have the same value as ``__spec__.parent``.
relative imports for main modules, as defined in :pep:`366`.

.. versionchanged:: 3.6
The value of ``__package__`` is expected to be the same as
Expand Down
24 changes: 24 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import sys
import textwrap
from types import ModuleType, SimpleNamespace
import unittest
from test import support
from test.support import import_helper
Expand Down Expand Up @@ -885,6 +886,29 @@ def test_issue31566(self):
support.swap_item(globals(), '__file__', None):
self.assertRaises(UserWarning, self.module.warn, 'bar')

@support.cpython_only
def test_gh86298(self):
# warn_explicit() itself issues an ImportWarning when a module and
# module_globals are both given, and the named module has a __loader__
# != its __spec__.loader.
bar = ModuleType('bar')
# First, make the __loader__ != the __spec__.loader. This should
# trigger the ImportWarning inside warn_explicit().
bar.__loader__ = object()
bar.__spec__ = SimpleNamespace(loader=object())
with original_warnings.catch_warnings():
self.assertWarns(
ImportWarning, self.module.warn_explicit,
'warning!', RuntimeWarning,
'bar.py', 2, module='bar knee', module_globals=bar.__dict__)
# Now make the __loader__ == __spec__.loader. This will not raise the exception.
bar.__spec__.loader = bar.__loader__
with original_warnings.catch_warnings():
self.module.filterwarnings('error', category=ImportWarning)
self.module.warn_explicit(
'warning!', RuntimeWarning,
'bar.py', 2, module='bar knee', module_globals=bar.__dict__)


class WarningsDisplayTests(BaseTest):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
In cases where ``warnings.warn_explicit()`` consults the module's loader, an
``ImportWarning`` is issued when ``m.__loader__`` differs from
``m.__spec__.loader``.
48 changes: 41 additions & 7 deletions Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -977,25 +977,59 @@ warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
static PyObject *
get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno)
{
PyObject *loader;
PyObject *loader, *spec_loader;
PyObject *spec;
PyObject *module_name;
PyObject *get_source;
PyObject *source;
PyObject *source_list;
PyObject *source_line;

/* Check/get the requisite pieces needed for the loader. */
module_name = _PyDict_GetItemWithError(module_globals, &_Py_ID(__name__));
if (!module_name) {
return NULL;
}
Py_INCREF(module_name);

/* Check/get the requisite pieces needed for the loader. Get both the
__spec__.loader and __loader__ attributes and warn if they are not the
same.
*/
spec = _PyDict_GetItemWithError(module_globals, &_Py_ID(__spec__));
if (spec == NULL) {
Py_DECREF(module_name);
return NULL;
warsaw marked this conversation as resolved.
Show resolved Hide resolved
}
Py_INCREF(spec);

spec_loader = PyObject_GetAttrString(spec, "loader");
Py_DECREF(spec);
if (spec_loader == NULL) {
Py_DECREF(module_name);
return NULL;
}

loader = _PyDict_GetItemWithError(module_globals, &_Py_ID(__loader__));
if (loader == NULL) {
Py_DECREF(spec_loader);
Py_DECREF(module_name);
return NULL;
}
Py_INCREF(loader);
module_name = _PyDict_GetItemWithError(module_globals, &_Py_ID(__name__));
if (!module_name) {
Py_DECREF(loader);
return NULL;

if (spec_loader != loader) {
int error = PyErr_WarnFormat(
PyExc_ImportWarning, 2,
"Module %U; __loader__ != __spec__.loader (%R != %R)",
module_name, spec_loader, loader);
if (error < 0) {
Py_DECREF(module_name);
Py_DECREF(spec_loader);
Py_DECREF(loader);
return NULL;
}
}
Py_INCREF(module_name);
Py_DECREF(spec_loader);

/* Make sure the loader implements the optional get_source() method. */
(void)_PyObject_LookupAttr(loader, &_Py_ID(get_source), &get_source);
Expand Down