|
| 1 | +# Copyright The Lightning AI team. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +import importlib |
| 15 | +from functools import lru_cache |
| 16 | +from importlib.util import find_spec |
| 17 | +from typing import Optional, TypeVar |
| 18 | + |
| 19 | +import pkg_resources |
| 20 | +from typing_extensions import ParamSpec |
| 21 | + |
| 22 | +T = TypeVar("T") |
| 23 | +P = ParamSpec("P") |
| 24 | + |
| 25 | + |
| 26 | +@lru_cache |
| 27 | +def package_available(package_name: str) -> bool: |
| 28 | + """Check if a package is available in your environment. |
| 29 | +
|
| 30 | + >>> package_available('os') |
| 31 | + True |
| 32 | + >>> package_available('bla') |
| 33 | + False |
| 34 | +
|
| 35 | + """ |
| 36 | + try: |
| 37 | + return find_spec(package_name) is not None |
| 38 | + except ModuleNotFoundError: |
| 39 | + return False |
| 40 | + |
| 41 | + |
| 42 | +@lru_cache |
| 43 | +def module_available(module_path: str) -> bool: |
| 44 | + """Check if a module path is available in your environment. |
| 45 | +
|
| 46 | + >>> module_available('os') |
| 47 | + True |
| 48 | + >>> module_available('os.bla') |
| 49 | + False |
| 50 | + >>> module_available('bla.bla') |
| 51 | + False |
| 52 | +
|
| 53 | + """ |
| 54 | + module_names = module_path.split(".") |
| 55 | + if not package_available(module_names[0]): |
| 56 | + return False |
| 57 | + try: |
| 58 | + importlib.import_module(module_path) |
| 59 | + except ImportError: |
| 60 | + return False |
| 61 | + return True |
| 62 | + |
| 63 | + |
| 64 | +class RequirementCache: |
| 65 | + """Boolean-like class to check for requirement and module availability. |
| 66 | +
|
| 67 | + Args: |
| 68 | + requirement: The requirement to check, version specifiers are allowed. |
| 69 | + module: The optional module to try to import if the requirement check fails. |
| 70 | +
|
| 71 | + >>> RequirementCache("torch>=0.1") |
| 72 | + Requirement 'torch>=0.1' met |
| 73 | + >>> bool(RequirementCache("torch>=0.1")) |
| 74 | + True |
| 75 | + >>> bool(RequirementCache("torch>100.0")) |
| 76 | + False |
| 77 | + >>> RequirementCache("torch") |
| 78 | + Requirement 'torch' met |
| 79 | + >>> bool(RequirementCache("torch")) |
| 80 | + True |
| 81 | + >>> bool(RequirementCache("unknown_package")) |
| 82 | + False |
| 83 | +
|
| 84 | + """ |
| 85 | + |
| 86 | + def __init__(self, requirement: str, module: Optional[str] = None) -> None: |
| 87 | + self.requirement = requirement |
| 88 | + self.module = module |
| 89 | + |
| 90 | + def _check_requirement(self) -> None: |
| 91 | + if hasattr(self, "available"): |
| 92 | + return |
| 93 | + try: |
| 94 | + # first try the pkg_resources requirement |
| 95 | + pkg_resources.require(self.requirement) |
| 96 | + self.available = True |
| 97 | + self.message = f"Requirement {self.requirement!r} met" |
| 98 | + except Exception as ex: |
| 99 | + self.available = False |
| 100 | + self.message = f"{ex.__class__.__name__}: {ex}. HINT: Try running `pip install -U {self.requirement!r}`" |
| 101 | + requirement_contains_version_specifier = any(c in self.requirement for c in "=<>") |
| 102 | + if not requirement_contains_version_specifier or self.module is not None: |
| 103 | + module = self.requirement if self.module is None else self.module |
| 104 | + # sometimes `pkg_resources.require()` fails but the module is importable |
| 105 | + self.available = module_available(module) |
| 106 | + if self.available: |
| 107 | + self.message = f"Module {module!r} available" |
| 108 | + |
| 109 | + def __bool__(self) -> bool: |
| 110 | + """Format as bool.""" |
| 111 | + self._check_requirement() |
| 112 | + return self.available |
| 113 | + |
| 114 | + def __str__(self) -> str: |
| 115 | + """Format as string.""" |
| 116 | + self._check_requirement() |
| 117 | + return self.message |
| 118 | + |
| 119 | + def __repr__(self) -> str: |
| 120 | + """Format as string.""" |
| 121 | + return self.__str__() |
0 commit comments