In this lesson, you’ll learn about a new module in the standard library in Python 3.8, importlib.metadata
.
Through this module, you can access information about installed packages in your Python installation. Together with its companion module, importlib.resources
, importlib.metadata
improves on the functionality of the older pkg_resources
.
As an example, you can get some information about pip
:
>>> from importlib import metadata
>>> metadata.version("pip")
'19.3.1'
>>> pip_metadata = metadata.metadata("pip")
>>> list(pip_metadata)
['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author',
'Author-email', 'License', 'Keywords', 'Platform', 'Classifier',
'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier',
'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier',
'Classifier', 'Classifier', 'Requires-Python']
>>> pip_metadata["Home-page"]
'https://pip.pypa.io/'
>>> pip_metadata["Requires-Python"]
'>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'
>>> len(metadata.files("pip"))
670
The currently installed version of pip
is 19.2.3. metadata()
gives access to most of the information that you can see on PyPI. You can for instance see that this version of pip
requires either Python 2.7, or Python 3.5 or higher. With files()
, you get a listing of all files that make up the pip
package. In this case, there are almost 700 files.
files()
returns a list of Path objects
. These give you a convenient way of looking into the source code of a package, using read_text()
. The following example prints out __init__.py
from the realpython-reader package:
>>> [p for p in metadata.files("realpython-reader") if p.suffix == ".py"]
[PackagePath('reader/__init__.py'), PackagePath('reader/__main__.py'),
PackagePath('reader/feed.py'), PackagePath('reader/viewer.py')]
>>> init_path = _[0] # Underscore access last returned value in the REPL
>>> print(init_path.read_text())
"""Real Python feed reader
Import the `feed` module to work with the Real Python feed:
>>> from reader import feed
>>> feed.get_titles()
['Logging in Python', 'The Best Python Books', ...]
See https://github.com/realpython/reader/ for more information
"""
# Version of realpython-reader package
__version__ = "1.0.0"
...
You can also access package dependencies:
>>> metadata.requires("realpython-reader")
['feedparser', 'html2text', 'importlib-resources', 'typing']
requires()
lists the dependencies of a package. You can see that realpython-reader
for instance uses feedparser in the background to read and parse a feed of articles.
See the documentation for more information about importlib.metadata
.