Skip to content

Commit

Permalink
Merge pull request #287 from python/feature/packages-distributions
Browse files Browse the repository at this point in the history
Add 'packages_distributions'.
  • Loading branch information
jaraco authored Feb 24, 2021
2 parents 73cf0a9 + 466cd3c commit aa9f799
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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)

0 comments on commit aa9f799

Please sign in to comment.