gh-135801: Fix inaccurate module info for SyntaxWarnings during AST parsing #135829
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
This commit addresses the inaccurate module information provided for SyntaxWarnings during AST parsing, specifically reported in issue #135801.
Previously,
_PyErr_EmitSyntaxWarning
(used by the compiler) relied on_PyErr_WarnExplicitObjectWithContext
to infer the module name from the call stack. During compilation, this often resulted in misleading module names likesys
orimportlib._bootstrap
, making it difficult to filter warnings effectively (e.g., using-W error::SyntaxWarning:test
).To resolve this, a new internal function
_PyErr_EmitSyntaxWarningFromCompiler
was introduced inPython/errors.c
. This function explicitly callsPyErr_WarnExplicitObject
with aNULL
module argument, forcing the warning system to derive the module name from the filename provided by the compiler.The
normalize_module
function inPython/_warnings.c
was also refined. Instead of simple string manipulation or problematic pure C path parsing, it now leverages Python'sos.path
module (via Python C API calls likebasename
,splitext
, anddirname
). This ensures robust and accurate extraction of module names from arbitrary file paths, including correct handling of__init__.py
files, thereby providing correct module information for compiler-generatedSyntaxWarning
messages.This approach ensures cross-platform compatibility and reliability by utilizing Python's battle-tested path handling capabilities, directly addressing the core issue reported.