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)