Skip to content

Commit 8d4b8d3

Browse files
fix(internal): improve performance of package resolution [backport 2.20] (#12376)
Co-authored-by: Brett Langdon <[email protected]>
1 parent 0ec7247 commit 8d4b8d3

File tree

3 files changed

+20
-10
lines changed

3 files changed

+20
-10
lines changed

.gitlab/benchmarks.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ microbenchmarks:
5656
- "http_propagation_extract"
5757
- "http_propagation_inject"
5858
- "rate_limiter"
59+
- "packages_update_imported_dependencies"
5960

6061
benchmarks-pr-comment:
6162
image: $MICROBENCHMARKS_CI_IMAGE

ddtrace/internal/packages.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020

2121
Distribution = t.NamedTuple("Distribution", [("name", str), ("version", str), ("path", t.Optional[str])])
2222

23+
_PACKAGE_DISTRIBUTIONS: t.Optional[t.Mapping[str, t.List[str]]] = None
24+
2325

2426
@callonce
2527
def get_distributions():
@@ -45,18 +47,21 @@ def get_distributions():
4547
return pkgs
4648

4749

48-
@cached(maxsize=1)
4950
def get_package_distributions() -> t.Mapping[str, t.List[str]]:
5051
"""a mapping of importable package names to their distribution name(s)"""
51-
try:
52-
import importlib.metadata as importlib_metadata
53-
except ImportError:
54-
import importlib_metadata # type: ignore[no-redef]
55-
56-
# Prefer the official API if available, otherwise fallback to the vendored version
57-
if hasattr(importlib_metadata, "packages_distributions"):
58-
return importlib_metadata.packages_distributions()
59-
return _packages_distributions()
52+
global _PACKAGE_DISTRIBUTIONS
53+
if _PACKAGE_DISTRIBUTIONS is None:
54+
try:
55+
import importlib.metadata as importlib_metadata
56+
except ImportError:
57+
import importlib_metadata # type: ignore[no-redef]
58+
59+
# Prefer the official API if available, otherwise fallback to the vendored version
60+
if hasattr(importlib_metadata, "packages_distributions"):
61+
_PACKAGE_DISTRIBUTIONS = importlib_metadata.packages_distributions()
62+
else:
63+
_PACKAGE_DISTRIBUTIONS = _packages_distributions()
64+
return _PACKAGE_DISTRIBUTIONS
6065

6166

6267
@cached(maxsize=1024)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
fixes:
3+
- |
4+
internal: Fix performance overhead of Python distribution parsing for internal telemetry.

0 commit comments

Comments
 (0)