Skip to content

fix(utils): look up package versions without scanning all installed packages - #8215

Open
Shellghostt wants to merge 1 commit into
getsentry:masterfrom
Shellghostt:fix-package-version-lookup
Open

Shellghostt wants to merge 1 commit into
getsentry:masterfrom
Shellghostt:fix-package-version-lookup

Conversation

@Shellghostt

Copy link
Copy Markdown

Description

package_version() in sentry_sdk/utils.py rebuilt the full installed-package mapping on every call: _get_installed_modules() iterates importlib.metadata.distributions() (parsing every installed distribution's metadata), and package_version additionally re-normalized that whole mapping per call. Integrations call package_version during sentry_sdk.init() to check minimum versions, so in environments with a few hundred installed packages this scan measurably slowed SDK startup.

This change makes package_version look up the single requested distribution with importlib.metadata.version() instead:

  • Top-level guarded from importlib import metadata as importlib_metadata (no inline imports, per the repo guidelines); PackageNotFoundError maps to None, matching the previous behaviour for missing packages.
  • The existing _get_installed_modules() scan remains as the fallback for environments without importlib.metadata (Python < 3.8), so supported old interpreters keep working.
  • Name handling is unchanged: the requested name is PEP 503-normalized first, which is also how importlib.metadata.version() resolves distribution names.

Tests in tests/test_utils.py:

  • test_package_version_installed_package asserts an installed package (pytest) resolves to the same parsed version as importlib.metadata.
  • test_package_version_does_not_scan_all_installed_packages monkeypatches _get_installed_modules to fail if invoked (the only way to assert the scan no longer happens) and asserts both hit and miss lookups still work.

Validation:

  • TESTPATH=tests/test_utils.py uv run tox -e py3.12-common -- -k package_version — 3 passed.
  • uv run ruff check / ruff format --check on the changed files — clean.
  • uv run --group typing mypy sentry_sdk — no issues in 203 files.

Issues

Reminders

  • Tests added and linted with uv run ruff as requested.
  • PR title uses conventional-commit style.

@Shellghostt
Shellghostt requested a review from a team as a code owner November 8, 2026 02:35

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

package_version() parses every installed package's metadata, slowing sentry_sdk.init()

1 participant