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

Introduce ModuleAvailableCache #86

Merged
merged 2 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/lightning_utilities/core/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,42 @@ def __repr__(self) -> str:
return self.__str__()


class ModuleAvailableCache:
"""Boolean-like class for check of module availability.

>>> ModuleAvailableCache("torch")
Module 'torch' available
>>> bool(ModuleAvailableCache("torch"))
True
>>> bool(ModuleAvailableCache("unknown_package"))
False
"""

def __init__(self, module: str) -> None:
self.module = module

def _check_requirement(self) -> None:
if hasattr(self, "available"):
return

self.available = module_available(self.module)
if self.available:
self.message = f"Module {self.module!r} available"
else:
self.message = f"Module not found: {self.module!r}. HINT: Try running `pip install -U {self.module}`"

def __bool__(self) -> bool:
self._check_requirement()
return self.available

def __str__(self) -> str:
self._check_requirement()
return self.message

def __repr__(self) -> str:
return self.__str__()


def get_dependency_min_version_spec(package_name: str, dependency_name: str) -> str:
"""Returns the minimum version specifier of a dependency of a package.

Expand Down
7 changes: 7 additions & 0 deletions tests/unittests/core/test_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
get_dependency_min_version_spec,
lazy_import,
module_available,
ModuleAvailableCache,
RequirementCache,
requires,
)
Expand Down Expand Up @@ -52,6 +53,12 @@ def test_requirement_cache():
assert "pip install -U '-'" in str(RequirementCache("-"))


def test_module_available_cache():
assert ModuleAvailableCache("pytest")
assert not ModuleAvailableCache("this_module_is_not_installed")
assert "pip install -U this_module_is_not_installed" in str(ModuleAvailableCache("this_module_is_not_installed"))


def test_get_dependency_min_version_spec():
attrs_min_version_spec = get_dependency_min_version_spec("pytest", "attrs")
assert re.match(r"^>=[\d.]+$", attrs_min_version_spec)
Expand Down