importlib.metadata Reads Installed Versions

Read installed package versions with importlib.metadata, handle PackageNotFoundError, and inspect distribution metadata and files.

PythonConfig Management

Code

pythonsnippet
30 lines
import importlib.metadata as metadata


def describe(name: str) -> None:
    try:
        dist = metadata.distribution(name)
    except metadata.PackageNotFoundError:
        print(name, 'is not installed')
        return
    print(name, 'version:', dist.version)
    print('requires:', len(dist.requires or []))
    print('files:', len(dist.files or []))


def main() -> None:
    for name in ('pip', 'setuptools', 'devexamples-not-installed'):
        describe(name)

    distributions = list(metadata.distributions())
    print('installed distributions:', len(distributions))
    names = sorted(
        dist.metadata['Name']
        for dist in distributions
        if dist.metadata['Name']
    )
    print('first names:', names[:5])


if __name__ == '__main__':
    main()

How it works

importlib.metadata Reads Installed Versions is built around the functions describe and main.

Repetition is confined to for name in ('pip', 'setuptools', 'devexamples-not-installed') — the rest of the file is straight-line.

Points of care

  • Plan for an install step: importlib is a real dependency, resolved by the package manager.

Applying it

Signature: def describe(name: str) -> None

Running the file prints labeled results such as requires:, files:, installed distributions: — each operation’s effect is visible in the output.

Running the file executes main, which drives describe in order.

Statements that matter

def describe(name: str) -> None:
    try:
        dist = metadata.distribution(name)
    except metadata.PackageNotFoundError:
        print(name, 'is not installed')
        return
    print(name, 'version:', dist.version)
    print('requires:', len(dist.requires or []))
    print('files:', len(dist.files or []))

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `importlib`. Without it the snippet will not load.