Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23305

How to get the distribution name of an imported package in Python3.10+

$
0
0

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 listPackage    Version---------- -------pillow     10.3.0pip        24.0setuptools 69.5.1wheel      0.43.0
$ pythonPython 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linuxType "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').versionTraceback (most recent call last):  File "<stdin>", line 1, in <module>  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

Viewing all articles
Browse latest Browse all 23305

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>