]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit...
authorBarry Warsaw <barry@python.org>
Fri, 7 Oct 2022 02:32:53 +0000 (19:32 -0700)
committerGitHub <noreply@github.com>
Fri, 7 Oct 2022 02:32:53 +0000 (19:32 -0700)
commit13d44891426e0faf165f974f2e46907ab5b645a9
tree3f86e88601b8a5b551b854d30396ce93f87d17f3
parent27369ef56ffed8ab68abc201a52b259a065ed8d7
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
Doc/reference/import.rst
Lib/importlib/_bootstrap_external.py
Lib/test/test_importlib/import_/test_helpers.py
Misc/NEWS.d/next/Core and Builtins/2022-10-04-14-04-40.gh-issue-86298.QVM7G1.rst [new file with mode: 0644]
Python/_warnings.c