Skip to content

Optimize type checking range lookup with binary search#7

Open
DebanKsahu wants to merge 4 commits into
LukasNiessen:mainfrom
DebanKsahu:perf/_in_type_checking
Open

Optimize type checking range lookup with binary search#7
DebanKsahu wants to merge 4 commits into
LukasNiessen:mainfrom
DebanKsahu:perf/_in_type_checking

Conversation

@DebanKsahu
Copy link
Copy Markdown

Pull Request

Key changes include:

Functional Improvements:

  • Improved the logic for checking if an AST node is inside a TYPE_CHECKING block by sorting the ranges and using bisect_right for efficient range lookup in _in_type_checking, enhancing both correctness and performance.
  • Ensured that the list of ranges for TYPE_CHECKING blocks is always sorted before use, which is necessary for the new binary search approach.

Code Style and Readability:

  • All other changes are due to ruff format and ruff check --fix

Change Type

  • Bug fix
  • Feature
  • Documentation
  • Refactoring
  • Improvement

…ith binary search

Now `_find_type_checking_ranges()` will return a range array sorted by start line, and the lineno for any import node will be matched using binary search with the help of the `bisect` library for faster lookup.

Currently, this assumes that there are no overlapping ranges in the ranges array. Overlapping ranges can occur only when there are nested `if TYPE_CHECKING:` blocks.
@DebanKsahu DebanKsahu requested a review from LukasNiessen as a code owner May 28, 2026 05:37
Use `isinstance()` to ensure `node.lineno` is an integer before checking TYPE_CHECKING ranges.

This avoids returning `Any` from `_in_type_checking()` and fixes the mypy `no-any-return` error.
Replaced the inline normalization of file paths with a precomputed set
to improve performance and reduce redundant computations during graph
extraction.
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.

1 participant