Skip to content

Fix import after use in function incorrectly removed (#178) #178#321

Merged
hakancelikdev merged 1 commit intomainfrom
fix/import-after-use-in-function
Feb 18, 2026
Merged

Fix import after use in function incorrectly removed (#178) #178#321
hakancelikdev merged 1 commit intomainfrom
fix/import-after-use-in-function

Conversation

@hakancelikdev
Copy link
Owner

When a module-level import appears textually after a function that uses it, unimport incorrectly removed it. Function/async function bodies are deferred (only execute when called), so imports defined later at module scope are available at call time. Class bodies execute immediately, so the lineno check still applies for them.

Added Name._is_deferred_usage() that walks from the Name's scope toward the Import's scope — if any scope on the path is a FunctionDef or AsyncFunctionDef, the usage is deferred and the lineno check is relaxed.

Edge case tests cover: async functions, nested functions, class bodies (not deferred), methods inside classes, from-imports, and module-level sequential usage.

When a module-level import appears textually after a function that uses
it, unimport incorrectly removed it. Function/async function bodies are
deferred (only execute when called), so imports defined later at module
scope are available at call time. Class bodies execute immediately, so
the lineno check still applies for them.

Added Name._is_deferred_usage() that walks from the Name's scope toward
the Import's scope — if any scope on the path is a FunctionDef or
AsyncFunctionDef, the usage is deferred and the lineno check is relaxed.

Edge case tests cover: async functions, nested functions, class bodies
(not deferred), methods inside classes, from-imports, and module-level
sequential usage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@hakancelikdev hakancelikdev linked an issue Feb 18, 2026 that may be closed by this pull request
@hakancelikdev hakancelikdev merged commit f6cf9c5 into main Feb 18, 2026
35 checks passed
@hakancelikdev hakancelikdev deleted the fix/import-after-use-in-function branch February 18, 2026 06:57
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.

Import after use gets removed

1 participant