gh-135801: Fix inaccurate module info for SyntaxWarnings during AST parsing by heliang666s · Pull Request #135829 · python/cpython
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 like sys or importlib._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 in Python/errors.c. This function explicitly calls PyErr_WarnExplicitObject with a NULL module argument, forcing the warning system to derive the module name from the filename provided by the compiler.
The normalize_module function in Python/_warnings.c was also refined. Instead of simple string manipulation or problematic pure C path parsing, it now leverages Python's os.path module (via Python C API calls like basename, splitext, and dirname). 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-generated SyntaxWarning messages.
This approach ensures cross-platform compatibility and reliability by utilizing Python's battle-tested path handling capabilities, directly addressing the core issue reported.