cpython/Doc/reference
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
..
compound_stmts.rst gh-95975: Move except/*/finally ref labels to more precise locations (#95976) 2022-10-02 07:12:56 +02:00
datamodel.rst gh-93738: Documentation C syntax (:c:type:<C type> -> :c:expr:<C type>) (#97768) 2022-10-05 11:01:14 -07:00
executionmodel.rst bpo-12029: [doc] clarify that except does not match virtual subclasses of the specified exception type (GH-32027) 2022-03-21 20:41:35 +00:00
expressions.rst Docs: Fix backtick errors found by sphinx-lint (#97998) 2022-10-06 18:01:30 -07:00
grammar.rst bpo-42485: [Doc] Link to PEP 617 from full grammar specification (GH-23532) 2020-11-30 19:08:26 +00:00
import.rst gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() (GH-97803) 2022-10-06 19:32:53 -07:00
index.rst Merge from 3.2: remove unneeded "Release" and "Date" markers from index pages. 2012-10-28 11:10:24 -07:00
introduction.rst gh-91838: Use HTTPS links in docs for resources which redirect to HTTPS (GH-95527) 2022-08-04 10:13:49 +03:00
lexical_analysis.rst closes gh-96734: Update to Unicode 15.0.0. (GH-96809) 2022-09-13 15:45:12 -07:00
simple_stmts.rst Docs: Fix backtick errors found by sphinx-lint (#97998) 2022-10-06 18:01:30 -07:00
toplevel_components.rst bpo-41762: Fix usage of productionlist markup in the doc (GH-22281) 2020-09-18 09:10:15 +02:00