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

Use importlib.metadata for guess_version instead of importing the module #171

Merged
merged 11 commits into from
Sep 8, 2022
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 2.3.1

- Use `importlib.metadata` to guess version of package before fallback to `pkg.__version__`.

## 2.3.0

- Move to a package layout
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ optional-dependencies.test = [
"pytest>=7.1.3",
"pytest-cov>=3",
"pytest-mock>=3.8.2",
"virtualenv<21,>=20.16.4",
"virtualenv<21,>=20.16.5",
]
optional-dependencies.graphviz = [
"graphviz>=0.20.1",
Expand Down
11 changes: 11 additions & 0 deletions src/pipdeptree/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ def guess_version(pkg_key, default="?"):
:returns: version
:rtype: string
"""
try:
if sys.version_info >= (3, 8): # pragma: >=3.8 cover
import importlib.metadata as importlib_metadata
else: # pragma: <3.8 cover
import importlib_metadata
return importlib_metadata.version(pkg_key)
except ImportError:
pass
# Avoid AssertionError with setuptools, see https://github.com/tox-dev/pipdeptree/issues/162
if pkg_key in {"setuptools"}:
return default
try:
m = import_module(pkg_key)
except ImportError:
Expand Down
16 changes: 16 additions & 0 deletions tests/guess_version_setuptools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import sys

import pipdeptree

if sys.version_info >= (3, 8):
import importlib.metadata as importlib_metadata
else:
import importlib_metadata


def raise_import_error(name):
raise ImportError(name)


importlib_metadata.version = raise_import_error
print(pipdeptree.guess_version("setuptools"), end="")
8 changes: 8 additions & 0 deletions tests/test_pipdeptree.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import platform
import subprocess
import sys
from contextlib import contextmanager
from itertools import chain
from pathlib import Path
from tempfile import NamedTemporaryFile

try:
Expand Down Expand Up @@ -488,3 +490,9 @@ def test_custom_interpreter(tmp_path, monkeypatch, capfd, args_joined):
assert context.value.code == 1
assert not out
assert err == "graphviz functionality is not supported when querying" " non-host python\n"


def test_guess_version_setuptools():
script = Path(__file__).parent / "guess_version_setuptools.py"
output = subprocess.check_output([sys.executable, script], text=True)
assert output == "?"