Skip to content

package_to_distribution

Class info

🛈 DocStrings

clear_caches

clear_caches() -> None

Clear all function caches, the entry point cache included.

This should be called when the underlying package distributions might have changed, for example after installing or removing packages.

Example

clear_caches() # Clear all cached mappings

Source code in src/epregistry/package_to_distribution.py
def clear_caches() -> None:
    """Clear all function caches, the entry point cache included.

    This should be called when the underlying package distributions might have changed,
    for example after installing or removing packages.

    Example:
        >>> clear_caches()  # Clear all cached mappings
    """
    _get_normalized_pkg_dist_map.cache_clear()
    _get_normalized_dist_pkg_map.cache_clear()
    get_packages_distributions.cache_clear()
    _package_to_distributions_impl.cache_clear()
    package_to_distribution.cache_clear()
    _distribution_to_package_impl.cache_clear()
    distribution_to_packages.cache_clear()
    clear_entry_point_cache()

distribution_to_package

distribution_to_package(distribution_name: str, *, fallback: Literal[True]) -> str
distribution_to_package(distribution_name: str, *, fallback: Literal[False] = False) -> str | None
distribution_to_package(distribution_name: str, *, fallback: bool = False) -> str | None

Convert a distribution name to its primary package name.

If a distribution provides multiple packages, returns the primary one: the package named like the distribution, else the shortest name without a leading underscore (ties broken alphabetically). Use distribution_to_packages() to get all packages.

Parameters:

Name Type Description Default
distribution_name str

The name of the distribution

required
fallback bool

Returns a normalized best guess even if no mapping found

False

Returns:

Type Description
str | None

The primary package name if found, None otherwise

Example

distribution_to_package('Pillow') 'PIL' distribution_to_package('requests') 'requests' distribution_to_package('nonexistent') None

Source code in src/epregistry/package_to_distribution.py
def distribution_to_package(distribution_name: str, *, fallback: bool = False) -> str | None:
    """Convert a distribution name to its primary package name.

    If a distribution provides multiple packages, returns the primary one: the
    package named like the distribution, else the shortest name without a leading
    underscore (ties broken alphabetically). Use distribution_to_packages() to get
    all packages.

    Args:
        distribution_name: The name of the distribution
        fallback: Returns a normalized best guess even if no mapping found

    Returns:
        The primary package name if found, None otherwise

    Example:
        >>> distribution_to_package('Pillow')
        'PIL'
        >>> distribution_to_package('requests')
        'requests'
        >>> distribution_to_package('nonexistent')
        None
    """
    return _distribution_to_package_impl(distribution_name, fallback=fallback)

distribution_to_packages cached

distribution_to_packages(distribution_name: str) -> frozenset[str]

Convert a distribution name to all its package names.

Parameters:

Name Type Description Default
distribution_name str

The name of the distribution

required

Returns:

Type Description
frozenset[str]

A frozenset of the (importable) top-level package names of the distribution

Example

distribution_to_packages('Pillow') {'PIL'} distribution_to_packages('python-dateutil') {'dateutil'} distribution_to_packages('nonexistent') set()

Source code in src/epregistry/package_to_distribution.py
@lru_cache(maxsize=1024)
def distribution_to_packages(distribution_name: str) -> frozenset[str]:
    """Convert a distribution name to all its package names.

    Args:
        distribution_name: The name of the distribution

    Returns:
        A frozenset of the (importable) top-level package names of the distribution

    Example:
        >>> distribution_to_packages('Pillow')
        {'PIL'}
        >>> distribution_to_packages('python-dateutil')
        {'dateutil'}
        >>> distribution_to_packages('nonexistent')
        set()
    """
    normalized_dist = distribution_name.lower().replace("-", "_")
    normalized_map = _get_normalized_dist_pkg_map()
    return normalized_map.get(normalized_dist, frozenset())

get_cache_info

get_cache_info() -> dict[str, str]

Get information about the current state of all caches.

Returns:

Type Description
dict[str, str]

A dictionary with cache statistics for each cached function

Example

info = get_cache_info() print(info['package_to_distribution']) 'CacheInfo(hits=42, misses=10, maxsize=1024, currsize=10)'

Source code in src/epregistry/package_to_distribution.py
def get_cache_info() -> dict[str, str]:
    """Get information about the current state of all caches.

    Returns:
        A dictionary with cache statistics for each cached function

    Example:
        >>> info = get_cache_info()
        >>> print(info['package_to_distribution'])
        'CacheInfo(hits=42, misses=10, maxsize=1024, currsize=10)'
    """
    return {
        "normalized_pkg_dist_map": str(_get_normalized_pkg_dist_map.cache_info()),
        "normalized_dist_pkg_map": str(_get_normalized_dist_pkg_map.cache_info()),
        "get_packages_distributions": str(get_packages_distributions.cache_info()),
        "package_to_distribution": str(package_to_distribution.cache_info()),
        "package_to_distributions": str(_package_to_distributions_impl.cache_info()),
        "distribution_to_package": str(_distribution_to_package_impl.cache_info()),
        "distribution_to_packages": str(distribution_to_packages.cache_info()),
    }

get_packages_distributions cached

get_packages_distributions() -> Mapping[str, Sequence[str]]

Cached call for packages_distributions (read-only).

Extends the stdlib mapping with packages of .pth-based editable installs which packages_distributions() does not report.

Source code in src/epregistry/package_to_distribution.py
@cache
def get_packages_distributions() -> Mapping[str, Sequence[str]]:
    """Cached call for packages_distributions (read-only).

    Extends the stdlib mapping with packages of .pth-based editable installs
    which `packages_distributions()` does not report.
    """
    mapping = {pkg: list(dists) for pkg, dists in packages_distributions().items()}
    known = {dist for dists in mapping.values() for dist in dists}
    for dist in distributions():
        name = dist.metadata.get("Name")
        if not name or name in known:
            continue
        for pkg in _editable_packages(dist):
            mapping.setdefault(pkg, []).append(name)
    return MappingProxyType({pkg: tuple(dists) for pkg, dists in mapping.items()})

package_to_distribution cached

package_to_distribution(package_name: str) -> str | None

Convert a package name to its distribution name.

Parameters:

Name Type Description Default
package_name str

The name of the package

required

Returns:

Type Description
str | None

The distribution name if found, None otherwise

Example

package_to_distribution('PIL') 'Pillow' package_to_distribution('requests') 'requests' package_to_distribution('nonexistent') None

Source code in src/epregistry/package_to_distribution.py
@lru_cache(maxsize=1024)
def package_to_distribution(package_name: str) -> str | None:
    """Convert a package name to its distribution name.

    Args:
        package_name: The name of the package

    Returns:
        The distribution name if found, None otherwise

    Example:
        >>> package_to_distribution('PIL')
        'Pillow'
        >>> package_to_distribution('requests')
        'requests'
        >>> package_to_distribution('nonexistent')
        None
    """
    if not isinstance(package_name, str):
        msg = "Package name must be a string"
        raise TypeError(msg)

    # First try direct lookup
    pkg_dist_map = get_packages_distributions()
    if package_name in pkg_dist_map:
        return pkg_dist_map[package_name][0]

    # Try normalized lookup with and without underscore prefix
    try:
        normalized_package = package_name.lower().replace("-", "_")
    except (TypeError, AttributeError) as e:
        msg = "Package name must be a string"
        raise TypeError(msg) from e

    normalized_map = _get_normalized_pkg_dist_map()

    # Try exact match first
    if normalized_package in normalized_map:
        return normalized_map[normalized_package]

    # Try without underscore prefix
    clean_package = normalized_package.lstrip("_")
    if clean_package != normalized_package and clean_package in normalized_map:
        return normalized_map[clean_package]
    return None

package_to_distributions

package_to_distributions(package_name: str) -> list[str] | None

Convert a package name to all its distribution names.

Parameters:

Name Type Description Default
package_name str

The name of the package

required

Returns:

Type Description
list[str] | None

List of distribution names if found, None otherwise.

Example

package_to_distributions('zope') # namespace package ['zope.interface', 'zope.event'] # if both are installed package_to_distributions('requests') ['requests'] package_to_distributions('nonexistent') None

Notes

For namespace packages (like 'zope'), returns all related distributions. This is particularly useful for examining namespace package relationships.

Source code in src/epregistry/package_to_distribution.py
def package_to_distributions(package_name: str) -> list[str] | None:
    """Convert a package name to all its distribution names.

    Args:
        package_name: The name of the package

    Returns:
        List of distribution names if found, None otherwise.

    Example:
        >>> package_to_distributions('zope')  # namespace package
        ['zope.interface', 'zope.event']  # if both are installed
        >>> package_to_distributions('requests')
        ['requests']
        >>> package_to_distributions('nonexistent')
        None

    Notes:
        For namespace packages (like 'zope'), returns all related distributions.
        This is particularly useful for examining namespace package relationships.
    """
    dists = _package_to_distributions_impl(package_name)
    return list(dists) if dists is not None else None