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

Add 'packages_distributions'. #287

Merged
merged 1 commit into from Feb 24, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES.rst
@@ -1,3 +1,9 @@
v3.7.0
======

* #131: Added ``packages_distributions`` to conveniently
resolve a top-level package or module to its distribution(s).

v3.6.0
======

Expand Down
11 changes: 11 additions & 0 deletions docs/using.rst
Expand Up @@ -182,6 +182,17 @@ function::
["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]


Package distributions
---------------------

A convience method to resolve the distribution or
distributions (in the case of a namespace package) for top-level
Python packages or modules::

>>> packages_distributions()
{'importlib_metadata': ['importlib-metadata'], 'yaml': ['PyYAML'], 'jaraco': ['jaraco.classes', 'jaraco.functools'], ...}


Distributions
=============

Expand Down
20 changes: 18 additions & 2 deletions importlib_metadata/__init__.py
Expand Up @@ -12,7 +12,7 @@
import functools
import itertools
import posixpath
import collections
import collections.abc

from ._compat import (
NullFinder,
Expand All @@ -28,7 +28,7 @@
from importlib import import_module
from importlib.abc import MetaPathFinder
from itertools import starmap
from typing import Any, List, Optional, TypeVar, Union
from typing import Any, List, Mapping, Optional, TypeVar, Union


__all__ = [
Expand Down Expand Up @@ -796,3 +796,19 @@ def requires(distribution_name):
packaging.requirement.Requirement.
"""
return distribution(distribution_name).requires


def packages_distributions() -> Mapping[str, List[str]]:
"""
Return a mapping of top-level packages to their
distributions.

>>> pkgs = packages_distributions()
>>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
True
"""
pkg_to_dist = collections.defaultdict(list)
for dist in distributions():
for pkg in (dist.read_text('top_level.txt') or '').split():
pkg_to_dist[pkg].append(dist.metadata['Name'])
return dict(pkg_to_dist)