I have multiple distributions that each provide a Python package of the same name (because they have the same API and same functionality, just different implementations). I want to be able to report which one is currently installed and in use along with its version. importlib.metadata
seems to have the functionality I want, but from my testing it appears to just do a case and punctuation insensitive search on the distribution name, which works in the most of the time case where they are the same, but which can never be able to distinguish two distributions sharing the same absolute import path. I have also glanced at the implementation which shows an awful lot of abstraction, but not any other currently implemented options. Sigh. It’s enough to make one want to go back to writing shell scripts.
Here is a concrete example using common packages rather than my own. importlib can report the version of wheel because its absolute import path is the same as the distribution name, however if we want to know whether we are using the original PIL library or pillow, it no longer works.
`$ pip list
Package Version
pillow 10.3.0
pip 24.0
setuptools 69.5.1
wheel 0.43.0
$ python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
from importlib import import_module, metadata
import_module(‘wheel’)
<module ‘wheel’ from ‘/opt/virtualenvs/pillow/lib/python3.10/site-packages/wheel/init.py’>
import_module(‘PIL’)
<module ‘PIL’ from ‘/opt/virtualenvs/pillow/lib/python3.10/site-packages/PIL/init.py’>
metadata.distribution(‘wheel’).version
‘0.43.0’
metadata.distribution(‘PIL’).version
Traceback (most recent call last):
File “”, line 1, in
File “/usr/lib/python3.10/importlib/metadata/init.py”, line 969, in distribution
return Distribution.from_name(distribution_name)
File “/usr/lib/python3.10/importlib/metadata/init.py”, line 548, in from_name
raise PackageNotFoundError(name)
importlib.metadata.PackageNotFoundError: No package metadata was found for PIL
`