From 5563d9ba713fc26eb3843831a32011aad1c9cf77 Mon Sep 17 00:00:00 2001 From: anthony sottile Date: Wed, 4 Nov 2026 16:12:11 -0500 Subject: [PATCH] preserve filename in SyntaxWarnings --- src/flake8/processor.py | 2 +- tests/unit/test_file_processor.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/flake8/processor.py b/src/flake8/processor.py index b1742ca1..57e5c09c 100644 --- a/src/flake8/processor.py +++ b/src/flake8/processor.py @@ -237,7 +237,7 @@ def build_logical_line_tokens(self) -> _Logical: # noqa: C901 def build_ast(self) -> ast.AST: """Build an abstract syntax tree from the list of lines.""" - return ast.parse("".join(self.lines)) + return ast.parse("".join(self.lines), self.filename) def build_logical_line(self) -> tuple[str, str, _LogicalMapping]: """Build a logical line from the current tokens list.""" diff --git a/tests/unit/test_file_processor.py b/tests/unit/test_file_processor.py index 22c5bcfd..7948519f 100644 --- a/tests/unit/test_file_processor.py +++ b/tests/unit/test_file_processor.py @@ -296,6 +296,17 @@ def test_build_ast(default_options): assert isinstance(module, ast.Module) +def test_build_ast_preserves_filename_in_warnings(default_options): + file_processor = processor.FileProcessor( + 'fname.py', default_options, lines=[r"s = '\d'\n"], + ) + + # the SyntaxWarning is upgraded to error due to `filterwarnings` + with pytest.raises(SyntaxError) as excinfo: + file_processor.build_ast() + assert excinfo.value.filename == 'fname.py' + + def test_next_logical_line_updates_the_previous_logical_line(default_options): """Verify that we update our tracking of the previous logical line.""" file_processor = processor.FileProcessor(