importlib.metadata Reads Installed Versions
Read installed package versions with importlib.metadata, handle PackageNotFoundError, and inspect distribution metadata and files.
Code
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:
importlibis 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does this need from the package registry?
- These are real dependencies: `importlib`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.