Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: [python-package] remove unnecessary layer of try-catching in conditional imports #6745

Closed
wants to merge 1 commit into from

Conversation

jameslamb
Copy link
Collaborator

@jameslamb jameslamb commented Dec 11, 2024

Optional dependencies in this project are handled via a pattern like this in compat.py:

try:
    from sklearn.preprocessing import LabelEncoder
    # ... many more ...
    SKLEARN_INSTALLED = True
except ImportError:
    LabelEncoder = None
    SKLEARN_INSTALLED = False

That ensures that importing from lightgbm and lightgbm.sklearn still works even in environments where scikit-learn is not installed.

Given this protection, this additional layer of try-catching in the top-level __init__.py is unnecessary:

try:
from .sklearn import LGBMClassifier, LGBMModel, LGBMRanker, LGBMRegressor
except ImportError:
pass
try:

This proposes removing it, for the following reasons:

  • simplifies the code
  • makes debugging other import issues easier (see "Notes for Reviewers")
  • maybe speeds up imports a tiny bit? (I'm not sure)

Notes for Reviewers

The try-catches removed in this PR have been in lightgbm for 8+ years, since #97

How I tested this

Installed the library.

cmake -B build -S .
cmake --build build --target _lightgbm -j4
sh build-python.sh install --precompile

Tried importing uninstalling scikit-learn and them importing LGBMClassifier.

pip uninstall --yes scikit-learn scipy
python -c "from lightgbm import LGBMClassifier"

@jameslamb
Copy link
Collaborator Author

After thinking about it a bit, I decided against this... I think it's useful to have e.g. train(), Booster(), cv(), etc. still be importable even if some import error does slip into sklearn.py, like if for some reason inspect.signature was removed from the standard lib:

from inspect import signature

Sorry for the noise.

@jameslamb jameslamb closed this Dec 12, 2024
@jameslamb jameslamb deleted the python/remove-try-catches branch December 12, 2024 04:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant