Search code examples
pythonpippkg-resources

Incorrecto version of pip when using pkg_resources


I'm trying to gather information about several machines, each one of them running different Python versions and installed modules.

I tried the pkg_resources way, but after updating pip on one of them I'm seeing that the reported pip version is not correct: pkg_resources

Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
>>> dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
>>> dists
['pip==1.5.6', 'pycryptodome==3.9.9', 'requests==2.10.0', 'setuptools==2.1', 'urllib3==1.24.3']
>>> import pip
>>> pip.__version__
'19.1.1'
python -m pip freeze
DEPRECATION: Python 3.4 support has been deprecated. pip 19.1 will be the last one supporting it. Please upgrade your Python as
Python 3.4 won't be maintained after March 2019 (cf PEP 429).
pycryptodome==3.9.9
requests==2.10.0
urllib3==1.24.3

The other libraries are fine:

>>> import requests
>>> requests.__version__
'2.10.0'
>>> import urllib3
>>> urllib3.__version__
'1.24.3'

Why is this happening? Is there a reliable way to get a module version without importing it?


Solution

  • pkg_resources is not a reliable way to determine module versions. It often relies on cached metadata about installed packages, which may be outdated or not yet updated. You can use this

    import importlib.metadata
    
    def get_version(package_name):
        try:
            return importlib.metadata.version(package_name)
        except importlib.metadata.PackageNotFoundError:
            return None  # Package not found
    

    It returns the package version or None if the package is not installed

    print(get_version('pip'))
    print(get_version('nonexistent_package'))
    

    returns

    23.0.1
    None