[python-package] fix mypy errors related to eval result parsing in callbacks #6096
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.
Contributes to #3867.
Resolves the following errors from
mypy
:These are all
mypy
rightly identifying places in the callbacks code whereCallbackEnv.evaluation_result_list
is used unconditionally as if it contains a list...LightGBM/python-package/lightgbm/callback.py
Lines 126 to 128 in 921479b
... even though it's possible for it to be
None
.LightGBM/python-package/lightgbm/engine.py
Lines 269 to 274 in 921479b
This PR proposes defensively raising an informative error if
env.evaluation_result_list
is stillNone
when any of those codepaths are reached. These should never be encountered by user code, but if they are then they're replacing cryptic errors likeTypeError: 'NoneType' object is not subscriptable
with something clearer.Why not just enforce that
CallbackEnv.evaluation_result_list
is always a list and neverNone
?I'm afraid that that would break other integrations with
lightgbm
.evaluation_result_list
has been nullable since the earliest days of the Python package, 7+ years ago: #97. I think taking on these errors messages is preferable to risking that.Especially since I've learned tonight that other projects are relying on the callbacks mechanism to integration with
lightgbmm
, like:FLAML
(code link)autogluon
(code link)wandb
(code link)