scikit-base 0.8.1__py3-none-any.whl → 0.8.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: scikit-base
3
- Version: 0.8.1
3
+ Version: 0.8.2
4
4
  Summary: Base classes for sklearn-like parametric objects
5
5
  Author-email: sktime developers <sktime.toolbox@gmail.com>
6
6
  Maintainer: Franz Király
@@ -75,10 +75,10 @@ Requires-Dist: nbsphinx >=0.8.6 ; extra == 'docs'
75
75
  Requires-Dist: numpydoc ; extra == 'docs'
76
76
  Requires-Dist: pydata-sphinx-theme ; extra == 'docs'
77
77
  Requires-Dist: sphinx-issues <5.0.0 ; extra == 'docs'
78
- Requires-Dist: sphinx-gallery <0.17.0 ; extra == 'docs'
78
+ Requires-Dist: sphinx-gallery <0.18.0 ; extra == 'docs'
79
79
  Requires-Dist: sphinx-panels ; extra == 'docs'
80
80
  Requires-Dist: sphinx-design <0.7.0 ; extra == 'docs'
81
- Requires-Dist: Sphinx !=7.2.0,<8.0.0 ; extra == 'docs'
81
+ Requires-Dist: Sphinx !=7.2.0,<9.0.0 ; extra == 'docs'
82
82
  Requires-Dist: tabulate ; extra == 'docs'
83
83
  Provides-Extra: linters
84
84
  Requires-Dist: mypy ; extra == 'linters'
@@ -114,7 +114,7 @@ Requires-Dist: scikit-learn >=0.24.0 ; extra == 'test'
114
114
  `skbase` provides base classes for creating scikit-learn-like parametric objects,
115
115
  along with tools to make it easier to build your own packages that follow these design patterns.
116
116
 
117
- :rocket: Version 0.8.1 is now available. Check out our
117
+ :rocket: Version 0.8.2 is now available. Check out our
118
118
  [release notes](https://skbase.readthedocs.io/en/latest/changelog.html).
119
119
 
120
120
  | Overview | |
@@ -1,5 +1,5 @@
1
1
  docs/source/conf.py,sha256=kFc-4qkb0ZGD5cDej5KPJhMePp9kpVu6ZqFoF0fgovg,9951
2
- skbase/__init__.py,sha256=jicuZQgA7WNCyhMFQBTRDzUnL7dB0XNhHU2aejwwIB4,345
2
+ skbase/__init__.py,sha256=DIqf7QEkt2QDidE-9-ErW63rmELfeU2h8gu_iYsXzlY,345
3
3
  skbase/_exceptions.py,sha256=KXfcVa7Xit-w-Xs_qFSJOEa_Mfp1oJeiHEC3v4Z0h1Q,1112
4
4
  skbase/_nopytest_tests.py,sha256=npL5pibSgCpulEGw0NqLKcG0majh6xcdW5A4Zibf78s,1077
5
5
  skbase/base/__init__.py,sha256=5ZLlwJeyfKDA1lAylBJgZd3t5JY25xsgQB4waQnroa8,751
@@ -21,7 +21,7 @@ skbase/testing/utils/__init__.py,sha256=kaLuqQwJsCunRWsUb1JwTVG-iqXbzdUobuYHNHsB
21
21
  skbase/testing/utils/_conditional_fixtures.py,sha256=QwI7K28Lsy6RAkDP94goo8uWWvMzKKNOmXRFtc9RNtI,9890
22
22
  skbase/testing/utils/inspect.py,sha256=e6F7AIuDhBTpgK8KKmiuwxeggrMjC7DHuSAKA1jOU2A,761
23
23
  skbase/tests/__init__.py,sha256=d2_OTTnt0GX5otQsBuNAb1evg8C5Fi0JjqK2VsfMtXU,37
24
- skbase/tests/conftest.py,sha256=gU64Q6iCW6gzWtJNxQwqrkpCUWY8ht0H1AnToKZS1Gc,9497
24
+ skbase/tests/conftest.py,sha256=dSZMtEE6cGB76iWtrHQY0iLpLFUt6Ir8xKNmzpwo0PY,9673
25
25
  skbase/tests/test_base.py,sha256=kIhBDcTajAvrOh_BNX8gNuwDWhhGPc-jV6qGE5JPAUk,50827
26
26
  skbase/tests/test_baseestimator.py,sha256=fuzpwxjYzyl-Vrte1va4AWdbYElhWnED8W10236Xprc,4731
27
27
  skbase/tests/test_exceptions.py,sha256=wOdk7Gp8pvbhucna3_9FxTk9xFLjC9XNsGsVabQLYEE,629
@@ -39,7 +39,7 @@ skbase/utils/deep_equals/__init__.py,sha256=1II3GWV1c1s43y62IidMiTjjyOnE9MFysQ5A
39
39
  skbase/utils/deep_equals/_common.py,sha256=O0ODPJGwdq6G-KdeGoHgyote53tNcxu3y2jHvej3bdQ,1273
40
40
  skbase/utils/deep_equals/_deep_equals.py,sha256=DT6nE0p1IGsLb82h3JJu24_nWeNE2HI46eL2qPlqxbo,19151
41
41
  skbase/utils/dependencies/__init__.py,sha256=cCUa_P-RiDs4pW6cw51uYeoBMaMa9iycwiFkwqkIizc,419
42
- skbase/utils/dependencies/_dependencies.py,sha256=emca3oXmDXZd5ihVQdwuHUsPTterrUMbuhEgqIROAwA,14340
42
+ skbase/utils/dependencies/_dependencies.py,sha256=GRDKuzVqyo1SFRMOyHntYOMMKGr3vJ5414jJjtH3dao,21182
43
43
  skbase/utils/dependencies/tests/__init__.py,sha256=UqE6wenG-HffjT2Z974OLzmXG-M8PNOP9nUnNfqtfT4,74
44
44
  skbase/utils/dependencies/tests/test_check_dependencies.py,sha256=uxAC3gr4VWTlgctN90pnT1ra_UYkPxQHEla-IljX-n0,2238
45
45
  skbase/utils/tests/__init__.py,sha256=YfvP5lpCrTC_6SIakU7jBBdqYyuqE07nZ56ZYKTs3f0,165
@@ -55,9 +55,9 @@ skbase/validate/_types.py,sha256=riVEVlj8ipErZX07OVbzv6zdGKssfegHyMr8XwaBm6M,121
55
55
  skbase/validate/tests/__init__.py,sha256=wunQBy6rajyrDymKvuFVajsBjj90VP5IFey5b6ZIRCk,70
56
56
  skbase/validate/tests/test_iterable_named_objects.py,sha256=NaEwdmtQJJy4GXMSh9ULOaR4ua7R11BcE6Khz5RKWUk,7438
57
57
  skbase/validate/tests/test_type_validations.py,sha256=oIysbDxRlbBMcCOrDMW6MM6VqhhMWJxNP6NO9Id9Q5g,14133
58
- scikit_base-0.8.1.dist-info/LICENSE,sha256=W2h8EYZ_G_mvCmCmXTTYqv66QF5NgSMbzLYJdk8qHVg,1525
59
- scikit_base-0.8.1.dist-info/METADATA,sha256=dwSrgzJLUtgNrpL8yN2yhCKgNQcSQRvVdJV_6ZQCIyY,8529
60
- scikit_base-0.8.1.dist-info/WHEEL,sha256=cpQTJ5IWu9CdaPViMhC9YzF8gZuS5-vlfoFihTBC86A,91
61
- scikit_base-0.8.1.dist-info/top_level.txt,sha256=FbRMsZcP-O6pMLGZpxA5pQ-ClfRzoB6Yr-hTViYqwT0,57
62
- scikit_base-0.8.1.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
63
- scikit_base-0.8.1.dist-info/RECORD,,
58
+ scikit_base-0.8.2.dist-info/LICENSE,sha256=W2h8EYZ_G_mvCmCmXTTYqv66QF5NgSMbzLYJdk8qHVg,1525
59
+ scikit_base-0.8.2.dist-info/METADATA,sha256=8kQ1XizgepOCLIkY1WdFrBLJl6ShYR5_pm_Pqr1tyW0,8529
60
+ scikit_base-0.8.2.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
61
+ scikit_base-0.8.2.dist-info/top_level.txt,sha256=FbRMsZcP-O6pMLGZpxA5pQ-ClfRzoB6Yr-hTViYqwT0,57
62
+ scikit_base-0.8.2.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
63
+ scikit_base-0.8.2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.1.0)
2
+ Generator: setuptools (72.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
skbase/__init__.py CHANGED
@@ -6,4 +6,4 @@
6
6
  The included functionality makes it easy to reuse scikit-learn and
7
7
  sktime design principles in your project.
8
8
  """
9
- __version__: str = "0.8.1"
9
+ __version__: str = "0.8.2"
skbase/tests/conftest.py CHANGED
@@ -251,7 +251,12 @@ SKBASE_FUNCTIONS_BY_MODULE.update(
251
251
  "skbase.utils.dependencies._dependencies": (
252
252
  "_check_soft_dependencies",
253
253
  "_check_python_version",
254
+ "_check_env_marker",
254
255
  "_check_estimator_deps",
256
+ "_get_pkg_version",
257
+ "_get_installed_packages",
258
+ "_normalize_requirement",
259
+ "_raise_at_severity",
255
260
  ),
256
261
  "skbase.utils.random_state": (
257
262
  "check_random_state",
@@ -2,25 +2,24 @@
2
2
  """Utility to check soft dependency imports, and raise warnings or errors."""
3
3
  import sys
4
4
  import warnings
5
- from importlib import import_module
5
+ from functools import lru_cache
6
+ from importlib.metadata import distributions
6
7
  from inspect import isclass
7
- from typing import List
8
8
 
9
+ from packaging.markers import InvalidMarker, Marker
9
10
  from packaging.requirements import InvalidRequirement, Requirement
10
- from packaging.specifiers import InvalidSpecifier, SpecifierSet
11
-
12
- from skbase.utils.stdout_mute import StdoutMute
13
-
14
- __author__: List[str] = ["fkiraly", "mloning"]
11
+ from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
12
+ from packaging.version import InvalidVersion, Version
15
13
 
16
14
 
15
+ # todo 0.10.0: remove suppress_import_stdout argument
17
16
  def _check_soft_dependencies(
18
17
  *packages,
19
- package_import_alias=None,
18
+ package_import_alias="deprecated",
20
19
  severity="error",
21
20
  obj=None,
22
21
  msg=None,
23
- suppress_import_stdout=False,
22
+ suppress_import_stdout="deprecated",
24
23
  ):
25
24
  """Check if required soft dependencies are installed and raise error or warning.
26
25
 
@@ -29,43 +28,63 @@ def _check_soft_dependencies(
29
28
  packages : str or list/tuple of str, or length-1-tuple containing list/tuple of str
30
29
  str should be package names and/or package version specifications to check.
31
30
  Each str must be a PEP 440 compatible specifier string, for a single package.
32
- For instance, the PEP 440 compatible package name such as "pandas";
33
- or a package requirement specifier string such as "pandas>1.2.3".
31
+ For instance, the PEP 440 compatible package name such as ``"pandas"``;
32
+ or a package requirement specifier string such as ``"pandas>1.2.3"``.
34
33
  arg can be str, kwargs tuple, or tuple/list of str, following calls are valid:
35
- `_check_soft_dependencies("package1")`
36
- `_check_soft_dependencies("package1", "package2")`
37
- `_check_soft_dependencies(("package1", "package2"))`
38
- `_check_soft_dependencies(["package1", "package2"])`
39
- package_import_alias : dict with str keys and values, optional, default=empty
40
- key-value pairs are package name, import name
41
- import name is str used in python import, i.e., from import_name import ...
42
- should be provided if import name differs from package name
34
+ ``_check_soft_dependencies("package1")``
35
+ ``_check_soft_dependencies("package1", "package2")``
36
+ ``_check_soft_dependencies(("package1", "package2"))``
37
+ ``_check_soft_dependencies(["package1", "package2"])``
38
+
39
+ package_import_alias : ignored, present only for backwards compatibility
40
+
43
41
  severity : str, "error" (default), "warning", "none"
44
- behaviour for raising errors or warnings
45
- "error" - raises a `ModuleNotFoundError` if one of packages is not installed
46
- "warning" - raises a warning if one of packages is not installed
47
- function returns False if one of packages is not installed, otherwise True
48
- "none" - does not raise exception or warning
49
- function returns False if one of packages is not installed, otherwise True
42
+ whether the check should raise an error, a warning, or nothing
43
+
44
+ * "error" - raises a ``ModuleNotFoundError`` if one of packages is not installed
45
+ * "warning" - raises a warning if one of packages is not installed
46
+ function returns False if one of packages is not installed, otherwise True
47
+ * "none" - does not raise exception or warning
48
+ function returns False if one of packages is not installed, otherwise True
49
+
50
50
  obj : python class, object, str, or None, default=None
51
51
  if self is passed here when _check_soft_dependencies is called within __init__,
52
52
  or a class is passed when it is called at the start of a single-class module,
53
53
  the error message is more informative and will refer to the class/object;
54
54
  if str is passed, will be used as name of the class/object or module
55
+
55
56
  msg : str, or None, default=None
56
57
  if str, will override the error message or warning shown with msg
57
- suppress_import_stdout : bool, optional. Default=False
58
- whether to suppress stdout printout upon import.
59
58
 
60
59
  Raises
61
60
  ------
61
+ InvalidRequirement
62
+ if package requirement strings are not PEP 440 compatible
62
63
  ModuleNotFoundError
63
64
  error with informative message, asking to install required soft dependencies
65
+ TypeError, ValueError
66
+ on invalid arguments
64
67
 
65
68
  Returns
66
69
  -------
67
70
  boolean - whether all packages are installed, only if no exception is raised
68
71
  """
72
+ # todo 0.10.0: remove this warning
73
+ if suppress_import_stdout != "deprecated":
74
+ warnings.warn(
75
+ "In skbase _check_soft_dependencies, the suppress_import_stdout argument "
76
+ "is deprecated and no longer has any effect. "
77
+ "The argument will be removed in version 0.10.0, so users of the "
78
+ "_check_soft_dependencies utility should not pass this argument anymore. "
79
+ "The _check_soft_dependencies utility also no longer causes imports, "
80
+ "hence no stdout "
81
+ "output is created from imports, for any setting of the "
82
+ "suppress_import_stdout argument. If you wish to import packages "
83
+ "and make use of stdout prints, import the package directly instead.",
84
+ DeprecationWarning,
85
+ stacklevel=2,
86
+ )
87
+
69
88
  if len(packages) == 1 and isinstance(packages[0], (tuple, list)):
70
89
  packages = packages[0]
71
90
  if not all(isinstance(x, str) for x in packages):
@@ -74,20 +93,6 @@ def _check_soft_dependencies(
74
93
  f"str, but found packages argument of type {type(packages)}"
75
94
  )
76
95
 
77
- if package_import_alias is None:
78
- package_import_alias = {}
79
- msg_pkg_import_alias = (
80
- "package_import_alias argument of _check_soft_dependencies must "
81
- "be a dict with str keys and values, but found "
82
- f"package_import_alias of type {type(package_import_alias)}"
83
- )
84
- if not isinstance(package_import_alias, dict):
85
- raise TypeError(msg_pkg_import_alias)
86
- if not all(isinstance(x, str) for x in package_import_alias.keys()):
87
- raise TypeError(msg_pkg_import_alias)
88
- if not all(isinstance(x, str) for x in package_import_alias.values()):
89
- raise TypeError(msg_pkg_import_alias)
90
-
91
96
  if obj is None:
92
97
  class_name = "This functionality"
93
98
  elif not isclass(obj):
@@ -112,6 +117,7 @@ def _check_soft_dependencies(
112
117
  for package in packages:
113
118
  try:
114
119
  req = Requirement(package)
120
+ req = _normalize_requirement(req)
115
121
  except InvalidRequirement:
116
122
  msg_version = (
117
123
  f"wrong format for package requirement string, "
@@ -124,53 +130,34 @@ def _check_soft_dependencies(
124
130
  package_name = req.name
125
131
  package_version_req = req.specifier
126
132
 
127
- # determine the package import
128
- if package_name in package_import_alias.keys():
129
- package_import_name = package_import_alias[package_name]
130
- else:
131
- package_import_name = package_name
132
- # attempt import - if not possible, we know we need to raise warning/exception
133
- try:
134
- with StdoutMute(active=suppress_import_stdout):
135
- pkg_ref = import_module(package_import_name)
136
- # if package cannot be imported, make the user aware of installation requirement
137
- except ModuleNotFoundError as e:
138
- if msg is None:
133
+ pkg_env_version = _get_pkg_version(package_name)
134
+
135
+ # if package not present, make the user aware of installation reqs
136
+ if pkg_env_version is None:
137
+ if obj is None and msg is None:
139
138
  msg = (
140
- f"{e}. "
141
139
  f"{class_name} requires package {package!r} to be present "
142
140
  f"in the python environment, but {package!r} was not found. "
143
141
  )
144
- if obj is not None:
145
- msg = msg + (
146
- f"{package!r} is a dependency of {class_name} and required "
147
- f"to construct it. "
148
- )
149
- msg = msg + (
150
- f"Please run: `pip install {package}` to "
151
- f"install the {package} package. "
142
+ elif msg is None: # obj is not None, msg is None
143
+ msg = (
144
+ f"{class_name} requires package {package!r} to be present "
145
+ f"in the python environment, but {package!r} was not found. "
146
+ f"{package!r} is a dependency of {class_name} and required "
147
+ f"to construct it. "
152
148
  )
149
+ msg = msg + (
150
+ f"Please run: `pip install {package}` to "
151
+ f"install the {package} package. "
152
+ )
153
153
  # if msg is not None, none of the above is executed,
154
154
  # so if msg is passed it overrides the default messages
155
155
 
156
- if severity == "error":
157
- raise ModuleNotFoundError(msg) from e
158
- elif severity == "warning":
159
- warnings.warn(msg, stacklevel=2)
160
- return False
161
- elif severity == "none":
162
- return False
163
- else:
164
- raise RuntimeError(
165
- "Error in calling _check_soft_dependencies, severity "
166
- 'argument must be "error", "warning", or "none",'
167
- f"found {severity!r}."
168
- ) from e
156
+ _raise_at_severity(msg, severity, caller="_check_soft_dependencies")
157
+ return False
169
158
 
170
159
  # now we check compatibility with the version specifier if non-empty
171
160
  if package_version_req != SpecifierSet(""):
172
- pkg_env_version = pkg_ref.__version__
173
-
174
161
  msg = (
175
162
  f"{class_name} requires package {package!r} to be present "
176
163
  f"in the python environment, with version {package_version_req}, "
@@ -184,23 +171,67 @@ def _check_soft_dependencies(
184
171
 
185
172
  # raise error/warning or return False if version is incompatible
186
173
  if pkg_env_version not in package_version_req:
187
- if severity == "error":
188
- raise ModuleNotFoundError(msg)
189
- elif severity == "warning":
190
- warnings.warn(msg, stacklevel=2)
191
- elif severity == "none":
192
- return False
193
- else:
194
- raise RuntimeError(
195
- "Error in calling _check_soft_dependencies, severity argument"
196
- f' must be "error", "warning", or "none", found {severity!r}.'
197
- )
174
+ _raise_at_severity(msg, severity, caller="_check_soft_dependencies")
175
+ return False
198
176
 
199
177
  # if package can be imported and no version issue was caught for any string,
200
178
  # then obj is compatible with the requirements and we should return True
201
179
  return True
202
180
 
203
181
 
182
+ @lru_cache
183
+ def _get_installed_packages_private():
184
+ """Get a dictionary of installed packages and their versions.
185
+
186
+ Same as _get_installed_packages, but internal to avoid mutating the lru_cache
187
+ by accident.
188
+ """
189
+ dists = distributions()
190
+ packages = {dist.metadata["Name"]: dist.version for dist in dists}
191
+ return packages
192
+
193
+
194
+ def _get_installed_packages():
195
+ """Get a dictionary of installed packages and their versions.
196
+
197
+ Returns
198
+ -------
199
+ dict : dictionary of installed packages and their versions
200
+ keys are PEP 440 compatible package names, values are package versions
201
+ MAJOR.MINOR.PATCH version format is used for versions, e.g., "1.2.3"
202
+ """
203
+ return _get_installed_packages_private().copy()
204
+
205
+
206
+ def _get_pkg_version(package_name):
207
+ """Check whether package is available in environment, and return its version if yes.
208
+
209
+ Returns ``Version`` object from ``lru_cache``, this should not be mutated.
210
+
211
+ Parameters
212
+ ----------
213
+ package_name : str, optional, default=None
214
+ name of package to check,
215
+ PEP 440 compatibe specifier string, e.g., "pandas" or "sklearn".
216
+ This is the pypi package name, not the import name, e.g.,
217
+ ``scikit-learn``, not ``sklearn``.
218
+
219
+ Returns
220
+ -------
221
+ None, if package is not found in python environment.
222
+ ``importlib`` ``Version`` of package, if present in environment.
223
+ """
224
+ pkgs = _get_installed_packages()
225
+ pkg_vers_str = pkgs.get(package_name, None)
226
+ if pkg_vers_str is None:
227
+ return None
228
+ try:
229
+ pkg_env_version = Version(pkg_vers_str)
230
+ except InvalidVersion:
231
+ pkg_env_version = None
232
+ return pkg_env_version
233
+
234
+
204
235
  def _check_python_version(obj, package=None, msg=None, severity="error"):
205
236
  """Check if system python version is compatible with requirements of obj.
206
237
 
@@ -208,13 +239,22 @@ def _check_python_version(obj, package=None, msg=None, severity="error"):
208
239
  ----------
209
240
  obj : BaseObject descendant
210
241
  used to check python version
242
+
211
243
  package : str, default = None
212
244
  if given, will be used in error message as package name
245
+
213
246
  msg : str, optional, default = default message (msg below)
214
- error message to be returned in the `ModuleNotFoundError`, overrides default
215
- severity : str, "error" (default), "warning", or "none"
247
+ error message to be returned in the ``ModuleNotFoundError``, overrides default
248
+
249
+ severity : str, "error" (default), "warning", "none"
216
250
  whether the check should raise an error, a warning, or nothing
217
251
 
252
+ * "error" - raises a ``ModuleNotFoundError`` if one of packages is not installed
253
+ * "warning" - raises a warning if one of packages is not installed
254
+ function returns False if one of packages is not installed, otherwise True
255
+ * "none" - does not raise exception or warning
256
+ function returns False if one of packages is not installed, otherwise True
257
+
218
258
  Returns
219
259
  -------
220
260
  compatible : bool, whether obj is compatible with system python version
@@ -247,6 +287,7 @@ def _check_python_version(obj, package=None, msg=None, severity="error"):
247
287
  if sys_version in est_specifier:
248
288
  return True
249
289
  # now we know that est_version is not compatible with sys_version
290
+
250
291
  if isclass(obj):
251
292
  class_name = obj.__name__
252
293
  else:
@@ -263,18 +304,80 @@ def _check_python_version(obj, package=None, msg=None, severity="error"):
263
304
  f" This is due to python version requirements of the {package} package."
264
305
  )
265
306
 
266
- if severity == "error":
267
- raise ModuleNotFoundError(msg)
268
- elif severity == "warning":
269
- warnings.warn(msg, stacklevel=2)
270
- elif severity == "none":
271
- return False
307
+ _raise_at_severity(msg, severity, caller="_check_python_version")
308
+ return False
309
+
310
+
311
+ def _check_env_marker(obj, package=None, msg=None, severity="error"):
312
+ """Check if packaging marker tag is with requirements of obj.
313
+
314
+ Parameters
315
+ ----------
316
+ obj : BaseObject descendant
317
+ used to check python version
318
+ package : str, default = None
319
+ if given, will be used in error message as package name
320
+ msg : str, optional, default = default message (msg below)
321
+ error message to be returned in the `ModuleNotFoundError`, overrides default
322
+
323
+ severity : str, "error" (default), "warning", "none"
324
+ whether the check should raise an error, a warning, or nothing
325
+
326
+ * "error" - raises a ``ModuleNotFoundError`` if one of packages is not installed
327
+ * "warning" - raises a warning if one of packages is not installed
328
+ function returns False if one of packages is not installed, otherwise True
329
+ * "none" - does not raise exception or warning
330
+ function returns False if one of packages is not installed, otherwise True
331
+
332
+ Returns
333
+ -------
334
+ compatible : bool, whether obj is compatible with system python version
335
+ check is using the python_version tag of obj
336
+
337
+ Raises
338
+ ------
339
+ InvalidMarker
340
+ User friendly error if obj has env_marker tag that is not a
341
+ packaging compatible marker string
342
+ ModuleNotFoundError
343
+ User friendly error if obj has an env_marker tag that is
344
+ incompatible with the python environment. If package is given,
345
+ error message gives package as the reason for incompatibility.
346
+ """
347
+ est_marker_tag = obj.get_class_tag("env_marker", tag_value_default="None")
348
+ if est_marker_tag in ["None", None]:
349
+ return True
350
+
351
+ try:
352
+ est_marker = Marker(est_marker_tag)
353
+ except InvalidMarker:
354
+ msg_version = (
355
+ f"wrong format for env_marker tag, "
356
+ f"must be PEP 508 compatible specifier string, e.g., "
357
+ f'platform_system!="windows", but found {est_marker_tag!r}'
358
+ )
359
+ raise InvalidMarker(msg_version) from None
360
+
361
+ if est_marker.evaluate():
362
+ return True
363
+ # now we know that est_marker is not compatible with the environment
364
+
365
+ if isclass(obj):
366
+ class_name = obj.__name__
272
367
  else:
273
- raise RuntimeError(
274
- "Error in calling _check_python_version, severity "
275
- f'argument must be "error", "warning", or "none", found {severity!r}.'
368
+ class_name = type(obj).__name__
369
+
370
+ if not isinstance(msg, str):
371
+ msg = (
372
+ f"{class_name} requires an environment to satisfy "
373
+ f"packaging marker spec {est_marker}, but environment does not satisfy it."
276
374
  )
277
- return True
375
+
376
+ if package is not None:
377
+ msg += f" This is due to requirements of the {package} package."
378
+
379
+ _raise_at_severity(msg, severity, caller="_check_env_marker")
380
+ return False
278
381
 
279
382
 
280
383
  def _check_estimator_deps(obj, msg=None, severity="error"):
@@ -288,17 +391,20 @@ def _check_estimator_deps(obj, msg=None, severity="error"):
288
391
 
289
392
  Parameters
290
393
  ----------
291
- obj : `BaseObject` descendant, instance or class, or list/tuple thereof
394
+ obj : BaseObject descendant, instance or class, or list/tuple thereof
292
395
  object(s) that this function checks compatibility of, with the python env
396
+
293
397
  msg : str, optional, default = default message (msg below)
294
- error message to be returned in the `ModuleNotFoundError`, overrides default
295
- severity : str, "error" (default), "warning", or "none"
296
- behaviour for raising errors or warnings
297
- "error" - raises a `ModuleNotFoundError` if environment is incompatible
298
- "warning" - raises a warning if environment is incompatible
299
- function returns False if environment is incompatible, otherwise True
300
- "none" - does not raise exception or warning
301
- function returns False if environment is incompatible, otherwise True
398
+ error message to be returned in the ``ModuleNotFoundError``, overrides default
399
+
400
+ severity : str, "error" (default), "warning", "none"
401
+ whether the check should raise an error, a warning, or nothing
402
+
403
+ * "error" - raises a ``ModuleNotFoundError`` if one of packages is not installed
404
+ * "warning" - raises a warning if one of packages is not installed
405
+ function returns False if one of packages is not installed, otherwise True
406
+ * "none" - does not raise exception or warning
407
+ function returns False if one of packages is not installed, otherwise True
302
408
 
303
409
  Returns
304
410
  -------
@@ -327,6 +433,7 @@ def _check_estimator_deps(obj, msg=None, severity="error"):
327
433
  return compatible
328
434
 
329
435
  compatible = compatible and _check_python_version(obj, severity=severity)
436
+ compatible = compatible and _check_env_marker(obj, severity=severity)
330
437
 
331
438
  pkg_deps = obj.get_class_tag("python_dependencies", None)
332
439
  pck_alias = obj.get_class_tag("python_dependencies_alias", None)
@@ -339,3 +446,97 @@ def _check_estimator_deps(obj, msg=None, severity="error"):
339
446
  compatible = compatible and pkg_deps_ok
340
447
 
341
448
  return compatible
449
+
450
+
451
+ def _normalize_requirement(req):
452
+ """Normalize packaging Requirement by removing build metadata from versions.
453
+
454
+ Parameters
455
+ ----------
456
+ req : packaging.requirements.Requirement
457
+ requirement string to normalize, e.g., Requirement("pandas>1.2.3+foobar")
458
+
459
+ Returns
460
+ -------
461
+ normalized_req : packaging.requirements.Requirement
462
+ normalized requirement object with build metadata removed from versions,
463
+ e.g., Requirement("pandas>1.2.3")
464
+ """
465
+ # Process each specifier in the requirement
466
+ normalized_specs = []
467
+ for spec in req.specifier:
468
+ # Parse the version and remove the build metadata
469
+ spec_v = Version(spec.version)
470
+ version_wo_build_metadata = f"{spec_v.major}.{spec_v.minor}.{spec_v.micro}"
471
+
472
+ # Create a new specifier without the build metadata
473
+ normalized_spec = Specifier(f"{spec.operator}{version_wo_build_metadata}")
474
+ normalized_specs.append(normalized_spec)
475
+
476
+ # Reconstruct the specifier set
477
+ normalized_specifier_set = SpecifierSet(",".join(str(s) for s in normalized_specs))
478
+
479
+ # Create a new Requirement object with the normalized specifiers
480
+ normalized_req = Requirement(f"{req.name}{normalized_specifier_set}")
481
+
482
+ return normalized_req
483
+
484
+
485
+ def _raise_at_severity(
486
+ msg,
487
+ severity,
488
+ exception_type=None,
489
+ warning_type=None,
490
+ stacklevel=2,
491
+ caller="_raise_at_severity",
492
+ ):
493
+ """Raise exception or warning or take no action, based on severity.
494
+
495
+ Parameters
496
+ ----------
497
+ msg : str
498
+ message to raise or warn
499
+
500
+ severity : str, "error" (default), "warning", "none"
501
+ whether the check should raise an error, a warning, or nothing
502
+
503
+ * "error" - raises a ``ModuleNotFoundError`` if one of packages is not installed
504
+ * "warning" - raises a warning if one of packages is not installed
505
+ function returns False if one of packages is not installed, otherwise True
506
+ * "none" - does not raise exception or warning
507
+ function returns False if one of packages is not installed, otherwise True
508
+
509
+ exception_type : Exception, default=ModuleNotFoundError
510
+ exception type to raise if severity="severity"
511
+ warning_type : warning, default=Warning
512
+ warning type to raise if severity="warning"
513
+ stacklevel : int, default=2
514
+ stacklevel for warnings, if severity="warning"
515
+ caller : str, default="_raise_at_severity"
516
+ caller name, used in exception if severity not in ["error", "warning", "none"]
517
+
518
+ Returns
519
+ -------
520
+ None
521
+
522
+ Raises
523
+ ------
524
+ exception : exception_type, if severity="error"
525
+ warning : warning+type, if severity="warning"
526
+ ValueError : if severity not in ["error", "warning", "none"]
527
+ """
528
+ if exception_type is None:
529
+ exception_type = ModuleNotFoundError
530
+
531
+ if severity == "error":
532
+ raise exception_type(msg)
533
+ elif severity == "warning":
534
+ warnings.warn(msg, category=warning_type, stacklevel=stacklevel)
535
+ elif severity == "none":
536
+ return None
537
+ else:
538
+ raise ValueError(
539
+ f"Error in calling {caller}, severity "
540
+ f'argument must be "error", "warning", or "none", found {severity!r}.'
541
+ )
542
+ return None