Skip to content

Commit 4f23a1b

Browse files
Fix false positive when import and usage are on the same line (#292) (#324)
Change strict less-than to less-than-or-equal in Name.match_2 lineno comparison so that semicolon-separated import+usage on the same line is correctly recognized as used. Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 1a56d4c commit 4f23a1b

File tree

4 files changed

+27
-2
lines changed

4 files changed

+27
-2
lines changed

src/unimport/statement.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,9 @@ def match_2(self, imp: Import | ImportFrom) -> bool:
167167
sub_match = (
168168
not primary_match and imp.is_match_sub_packages(self.name) and not self._has_more_specific_import(imp)
169169
)
170-
is_match = (imp.lineno < self.lineno or self._is_deferred_usage(imp)) and (primary_match or sub_match)
170+
is_match = (imp.lineno <= self.lineno or self._is_deferred_usage(imp)) and (primary_match or sub_match)
171171
else:
172-
is_match = (imp.lineno < self.lineno or self._is_deferred_usage(imp)) and (
172+
is_match = (imp.lineno <= self.lineno or self._is_deferred_usage(imp)) and (
173173
self.name == imp.name or imp.is_match_sub_packages(self.name)
174174
)
175175

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import Union
2+
3+
from unimport.statement import Import, ImportFrom, Name
4+
5+
__all__ = ["NAMES", "IMPORTS", "UNUSED_IMPORTS"]
6+
7+
8+
NAMES: list[Name] = [
9+
Name(lineno=1, name="print", is_all=False),
10+
Name(lineno=1, name="pathlib.Path", is_all=False),
11+
Name(lineno=1, name="__file__", is_all=False),
12+
Name(lineno=2, name="sys.exit", is_all=False),
13+
Name(lineno=2, name="doctest.testmod", is_all=False),
14+
Name(lineno=2, name="doctest.ELLIPSIS", is_all=False),
15+
]
16+
IMPORTS: list[Union[Import, ImportFrom]] = [
17+
Import(lineno=1, column=1, name="pathlib", package="pathlib"),
18+
Import(lineno=2, column=1, name="doctest", package="doctest"),
19+
Import(lineno=2, column=2, name="sys", package="sys"),
20+
]
21+
UNUSED_IMPORTS: list[Union[Import, ImportFrom]] = []
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
if True: import pathlib; print(pathlib.Path(__file__))
2+
if True: import doctest, sys; sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS)[0])
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
if True: import pathlib; print(pathlib.Path(__file__))
2+
if True: import doctest, sys; sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS)[0])

0 commit comments

Comments
 (0)