[python-package] add more type hints in basic.py #5729
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Contributes to #3756.
Adds some type hints
basic.py
."ctypes._Pointer'
as a type hint forctypes
pointers_InnerPredictor.__create_sparse_native()
,_InnerPredictor.__get_num_preds()
,_InnerPredictor.__pred_for_csr()
,_InnerPredictor.__pred_for_csc()
This improves
mypy
's ability to catch bugs, and makes it a bit easier to understand what the code is doing when reading it.Notes for Reviewers
Back in #5446, we talked about how to type-annotate
ctypes
pointers. At the time @StrikerRUS recommended usingctypes._Pointer
#5446 (comment) but I proposed just usingAny
, because I was afraid that the name_Pointer
beginning with_
meant that it was consider an internal implementation detail that might change in future versions ofctypes
.This PR proposes adopting that suggestion to use
ctypes._Pointer
. Since then, I've learned more about howmypy
evaluates type annotations.Specifically, per the
mypy
docs (link)I think that using a string-literal type hint means that if a future
ctypes
version removesctypes._Pointer
, it'll break type hinting but not actually cause runtime issues for users. Given that, I now support using the more specific type annotation to improvemypy
's ability to catch bugs.Consider the following example:
mypy
fails with an informative error.But the code runs without issue.