python / python/cpython

warn_explicit() discards the source line obtained from module_globals

Open
#155,319 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

3.13 3.14 3.15 3.16 extension-modules type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

The only purpose of the module_globals argument of warnings.warn_explicit() is to get the source line of the warning from the module loader when the file cannot be read. The C implementation computes it in get_source_line(), but then throws it away.

call_show_warning() passes None in the line slot of WarningMessage and ignores its own sourceline argument:

    msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
            filename, lineno_obj, Py_None, Py_None,
            source ? source : Py_None, module,
            NULL);

sourceline is only used in the fallback show_warning() path, taken when warnings._showwarnmsg is not available.

As a result the source line is lost, while the pure Python implementation, which seeds linecache instead, displays it:

$ cat > spam.py <<EOF
import warnings
def f():
    warnings.warn_explicit('eggs', UserWarning, 'bar', 1, module_globals=globals())
EOF
$ ./python -c 'import spam; spam.f()'
bar:1: UserWarning: eggs
$ ./python -c 'import sys; sys.modules["_warnings"] = None; import spam; spam.f()'
bar:1: UserWarning: eggs
  import warnings

The None was added in 914cde89d4c together with the source argument, so the C implementation has never passed the source line.

Linked PRs
  • gh-155320
  • gh-155824
  • gh-155825
  • gh-155826

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the C functions get_source_line() and call_show_warning(), which the issue identifies as computing and then discarding the source line. Reproduce the warn_explicit() examples from the issue and verify that the source line is preserved in the WarningMessage path as well as the fallback show_warning() path.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.