refactor: improve type hints in linear_search.py#14615
Conversation
- Add typing import for Any type - Update linear_search parameter types from list/int to list[Any]/Any - Update rec_linear_search parameter types from list/int to list[Any]/Any - Improves type safety and IDE support while maintaining functionality Fixes TheAlgorithms#14592
for more information, see https://pre-commit.ci
|
@cla-assistant please recheck |
TTAAAN
left a comment
There was a problem hiding this comment.
This is already a good approach. using list[Any] aligns with the documentation as it expects a generic type.
However, Any allows the user to pass in any type which is correct, but there's an edge case. What if the user passes in [1, 2, "3", [1, 2]]? Type checker wouldn't warn about this since it still falls under Any type.
A better type hint would be the generic type T = TypeVar("T") since it enforces the type consistency at the type-checking level.
Furthermore, the documentation expects a collection with comparable items. A better type hint would be Sequence instead of list. The current implementation would cause a type checker warning if the user tries to pass a tuple (1, 2, 5, 0).
Overall, I suggest changing it to Sequence[T].
As suggested by TTAAAN, using Sequence[T] with TypeVar provides better type consistency and allows the functions to accept tuples as well as lists.
|
Thanks @TTAAAN for the suggestion! I've updated the type hints to use |
|
Great progress. Actually I was exploring the codebase inside searching algorithm folder. I've found a stricter implementation from jump_search.py, the file used Protocol. Example implementation could be: class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
T = TypeVar("T", bound=Comparable)This forces the type checker to additionally check if the type implements the method defined. Furthermore, one of the test failed due to formatting issue, you could perform ruff check first before committing. You could read more here @TheAlgorithms/Python/files/CONTRIBUTING.md Output from the |
…feedback - Replace TypeVar with PEP 695 syntax [T: Comparable] - Add Comparable Protocol for stricter type checking - Use collections.abc.Sequence instead of typing.Sequence - Fix pre-commit formatting issues
|
Thanks @TTAAAN! I've updated the implementation to follow the same pattern as
The doctests all pass, and ruff check/format are clean. Let me know if any further changes are needed! |
Describe your change:
Improved type hints in searches/linear_search.py to better support searching for any comparable type, not just integers.
Checklist:
Fixes #14592