Skip to content

fix: allow removal of unused imports with trailing comments - #373

Open
AdamMagued wants to merge 1 commit into
PyCQA:mainfrom
AdamMagued:fix-trailing-comment-import-removal
Open

AdamMagued wants to merge 1 commit into
PyCQA:mainfrom
AdamMagued:fix-trailing-comment-import-removal

Conversation

@AdamMagued

Copy link
Copy Markdown

Summary

When an unused import line had a trailing comment (e.g. import unused_module # comment), autoflake previously skipped removal entirely because line iteration checked elif "#" in line: result = line before checking line_number in marked_import_line_numbers.

This PR addresses the issue by:

  • Checking line_number in marked_import_line_numbers before generic # comment checks, while continuing to respect # noqa directives via a dedicated is_noqa helper.
  • Ensuring _valid_char_in_line is used in multiline_import and multiline_statement so characters like (, ), :, and ; within inline comments do not incorrectly mark single-line imports as multiline.
  • Updating extract_package_name and filter_unused_import to operate on the code portion of the line when parsing package names and commas.
  • Preserving trailing comments in filter_from_import and break_up_import when only a subset of imports on the line are removed.
  • Permitting removal of the unused import line when only unused imports and trailing comments existed on the line.
  • Adding regression unit tests in test_autoflake.py covering single and multiple imports with trailing comments.

Fixes #106

Unused import lines with trailing inline comments were previously skipped
from removal because autoflake bypassed all lines containing "#" before
evaluating unused imports.

- Restrict inline comment bypass to "# noqa" directives.
- Update multiline check and extract_package_name to ignore characters in comments.
- Preserve trailing comments when only a subset of imported symbols on a line are removed.
- Allow full removal of unused import lines with trailing comments while maintaining block structure.
- Add regression tests covering import lines with trailing comments.

Fixes PyCQA#106
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Trailing comment prevents removal of unused imports

1 participant