cpython/Lib/importlib
Barry Warsaw 13d4489142
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
2022-10-06 19:32:53 -07:00
..
metadata gh-97781: Apply changes from importlib_metadata 5. (GH-97785) 2022-10-06 15:25:24 -04:00
resources gh-82874: Convert remaining importlib format uses to f-str. (#98005) 2022-10-06 18:27:51 -07:00
__init__.py gh-82874: Convert remaining importlib format uses to f-str. (#98005) 2022-10-06 18:27:51 -07:00
_abc.py gh-94619: Remove long deprecated methods module_repr() and load_module() (#94624) 2022-08-04 17:24:26 -07:00
_bootstrap.py bpo-38693: Use f-strings instead of str.format() within importlib (#17058) 2022-10-06 16:43:16 -07:00
_bootstrap_external.py gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() (GH-97803) 2022-10-06 19:32:53 -07:00
abc.py gh-93963: Officially deprecate abcs and warn about their usage. (GH-93965) 2022-07-03 12:17:27 -07:00
machinery.py bpo-35673: Add a public alias for namespace package __loader__ attribute (#29049) 2021-10-20 14:05:29 -07:00
readers.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
simple.py bpo-46118: Move importlib.resources to its own package. (#30176) 2021-12-30 21:00:48 -05:00
util.py gh-82874: Convert remaining importlib format uses to f-str. (#98005) 2022-10-06 18:27:51 -07:00