Skip to content

Commit fd07977

Browse files
ENH Adds lazy module at the top level (scikit-learn#29793)
Co-authored-by: Adrin Jalali <adrin.jalali@gmail.com>
1 parent a072e56 commit fd07977

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
- Scikit-learn classes and functions can be used while only having a
2+
`import sklearn` import line. For example, `import sklearn; sklearn.svm.SVC()` now works.
3+
By :user:`Thomas Fan <thomasjpfan>`

sklearn/__init__.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#
1717
# See https://scikit-learn.org for complete documentation.
1818

19+
import importlib as _importlib
1920
import logging
2021
import os
2122
import random
@@ -72,7 +73,7 @@
7273
from .base import clone # noqa: E402
7374
from .utils._show_versions import show_versions # noqa: E402
7475

75-
__all__ = [
76+
_submodules = [
7677
"calibration",
7778
"cluster",
7879
"covariance",
@@ -110,6 +111,9 @@
110111
"discriminant_analysis",
111112
"impute",
112113
"compose",
114+
]
115+
116+
__all__ = _submodules + [
113117
# Non-modules:
114118
"clone",
115119
"get_config",
@@ -118,6 +122,21 @@
118122
"show_versions",
119123
]
120124

125+
126+
def __dir__():
127+
return __all__
128+
129+
130+
def __getattr__(name):
131+
if name in _submodules:
132+
return _importlib.import_module(f"sklearn.{name}")
133+
else:
134+
try:
135+
return globals()[name]
136+
except KeyError:
137+
raise AttributeError(f"Module 'sklearn' has no attribute '{name}'")
138+
139+
121140
_BUILT_WITH_MESON = False
122141
try:
123142
import sklearn._built_with_meson # noqa: F401

0 commit comments

Comments
 (0)