From 8f1b8ff1fbbd39d53429e96d0377f991cfa0aa14 Mon Sep 17 00:00:00 2001 From: frankgoldfish Date: Tue, 17 Mar 2026 11:40:30 -0700 Subject: [PATCH] fix: handle missing 'import' keyword in break_up_import When source code contains carriage returns (\r) within parenthesized import statements, Python's io.StringIO.readlines() may produce continuation lines that don't contain the 'import' keyword. In such cases, re.split(r'\bimport\b', line) returns a list with only one element, causing a ValueError when trying to unpack to (indentation, imports). Fix: check the length of parts returned by re.split in break_up_import. If 'import' is not found in the line, return the line unchanged. Fixes #326 --- autoflake.py | 7 ++++++- test_autoflake.py | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/autoflake.py b/autoflake.py index 95a8153..4f30bb6 100755 --- a/autoflake.py +++ b/autoflake.py @@ -533,12 +533,17 @@ def break_up_import(line: str) -> str: if not newline: return line - indentation, imports = re.split( + parts = re.split( pattern=r"\bimport\b", string=line, maxsplit=1, ) + if len(parts) != 2: + # No 'import' keyword found (e.g., a continuation line with \r line endings) + return line + + indentation, imports = parts indentation += "import " assert newline diff --git a/test_autoflake.py b/test_autoflake.py index eacb0d1..2ec96bb 100755 --- a/test_autoflake.py +++ b/test_autoflake.py @@ -3619,3 +3619,23 @@ def write(*_: Any) -> None: if __name__ == "__main__": unittest.main() + + +class TestCarriageReturnInImport(unittest.TestCase): + """Tests for fix of crash with carriage return in multiline import (issue #326).""" + + def test_carriage_return_in_multiline_parenthesized_import(self): + """Should not crash when a line within parenthesized import starts with \r.""" + source = ( + "from t import (\n" + "\r a,\n" + " b,\n" + ")\n" + "from t import (\n" + " a,\n" + " b,\n" + ")\n" + ) + # Should not raise ValueError + result = autoflake.fix_code(source, remove_all_unused_imports=True) + self.assertIsNotNone(result)