How to get package metadata using importlib in Python
The metadata module
The metadata module in importlib module provides the metadata information about the installed modules. This module, along with importlib.resources module, replaces the older pkg_resources module.
Some of the metadata attributes are package version, name, description, and so on.
Note: Refer to Core metadata specifications to get all metadata attributes.
The metadata() method
The metadata() method of the metadata module provides all the core metadata specifications about a package.
Syntax
metadata.metadata(pkg_name)
The pkg_name is the package name.
Return value
The method returns an object that contains all metadata information about the package.
Code example
Let’s look at the code example:
from importlib import metadatasp_data = metadata.metadata("setuptools")print("Metadata about setuptools pacakge:")print("Version - ", sp_data['Version'])print("Summary - ", sp_data['Summary'])print("-"*8)print("Metadata dictionary - ")print(dict(sp_data))
Code explanation
- Line 1: We import the
metadatamodule. - Line 3: We retrieve the metadata about the
setuptoolspackage using themetadata()method. - Lines 5 to 6: We print the individual metadata attributes like the version and print the summary.
- Line 11: We print the dictionary representation of the object.