Skip to content

Commit

Permalink
Added get_dependency_min_version_spec function (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
mauvilsa authored Oct 27, 2022
1 parent 4de6e2b commit c3bcba0
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/lightning_utilities/core/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import importlib
import operator
from functools import lru_cache
from importlib import metadata
from importlib.util import find_spec
from typing import Callable

import pkg_resources
from packaging.requirements import Requirement
from packaging.version import Version


Expand Down Expand Up @@ -107,3 +109,21 @@ def __str__(self) -> str:

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.
>>> get_dependency_min_version_spec("pytorch-lightning", "jsonargparse")
'>=4.12.0'
"""
dependencies = metadata.requires(package_name) or []
for dep in dependencies:
dependency = Requirement(dep)
if dependency.name == dependency_name:
spec = [str(s) for s in dependency.specifier if str(s)[0] == ">"]
return spec[0] if spec else ""
raise ValueError(
"This is an internal error. Please file a GitHub issue with the error message. Dependency "
f"{dependency_name!r} not found in package {package_name!r}."
)
22 changes: 21 additions & 1 deletion tests/unittests/core/test_imports.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import operator
import re
from importlib.metadata import PackageNotFoundError

from lightning_utilities.core.imports import compare_version, module_available, RequirementCache
import pytest

from lightning_utilities.core.imports import (
compare_version,
get_dependency_min_version_spec,
module_available,
RequirementCache,
)


def test_module_exists():
Expand Down Expand Up @@ -38,3 +47,14 @@ def test_requirement_cache():
assert RequirementCache(f"pytest>={pytest.__version__}")
assert not RequirementCache(f"pytest<{pytest.__version__}")
assert "pip install -U '-'" in str(RequirementCache("-"))


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)

with pytest.raises(ValueError, match="'invalid' not found in package 'pytest'"):
get_dependency_min_version_spec("pytest", "invalid")

with pytest.raises(PackageNotFoundError, match="invalid"):
get_dependency_min_version_spec("invalid", "invalid")

0 comments on commit c3bcba0

Please sign in to comment.