How do I check the versions of Python modules?

To check the versions of Python modules, you can use command-line tools or in-script methods. Below are detailed approaches with examples:

1. Using pip (Command Line)

The most common method to check installed package versions.

a. Check a Specific Package

# Syntax
pip show <package_name>

# Example
pip show numpy

Output:

Name: numpy
Version: 1.26.4
Summary: Fundamental package for array computing in Python
...

b. List All Installed Packages

pip list  # Short list
pip freeze  # Detailed list (requirements format)

# Filter results (Unix/macOS)
pip list | grep numpy

# Filter results (Windows)
pip list | findstr numpy

2. Using __version__ Attribute (In Python Script)

Many packages expose their version via a __version__ attribute.

import numpy
import pandas as pd  # Aliased imports also work

print(numpy.__version__)  # Output: '1.26.4'
print(pd.__version__)     # Output: '2.2.1'

Note: Not all packages support __version__ (e.g., os or sys).
Alternative Attributes: Some packages use VERSION or version (check the package’s docs).

3. Using pkg_resources (Safe for Unimported Packages)

Use the pkg_resources module (part of setuptools) to check versions without importing the package.

import pkg_resources

# Check a single package
version = pkg_resources.get_distribution("numpy").version
print(version)  # Output: '1.26.4'

# List all installed packages
for pkg in pkg_resources.working_set:
    print(f"{pkg.key} == {pkg.version}")

4. Using importlib.metadata (Python 3.8+)

For modern Python versions, use the built-in importlib.metadata.

from importlib.metadata import version, distributions

# Check a single package
print(version("numpy"))  # Output: '1.26.4'

# List all installed packages
for dist in distributions():
    print(f"{dist.name} == {dist.version}")

5. Check Version Programmatically (Fallback Method)

Handle packages without a __version__ attribute.

import subprocess

def get_package_version(package_name):
    try:
        return __import__(package_name).__version__
    except AttributeError:
        # Use pip if __version__ is missing
        result = subprocess.run(
            ["pip", "show", package_name],
            capture_output=True,
            text=True
        )
        for line in result.stdout.splitlines():
            if line.startswith("Version:"):
                return line.split(": ")[1]
        return "Version not found"

print(get_package_version("requests"))

Common Scenarios & Fixes

Scenario 1: Package Not Found

  • Cause: The package is not installed in the current environment.
  • Fix: Use pip install <package> or check your Python environment.

Scenario 2: Multiple Versions Installed

  • Cause: Conflicting installations (e.g., global vs. virtual environment).
  • Fix: Use python -m pip show <package> to check the version in the current environment.

Scenario 3: Version Attribute Missing

  • Cause: The package doesn’t follow standard versioning conventions.
  • Fix: Use pip show or pkg_resources.

Summary

  1. For CLI: Use pip show <package> or pip list.
  2. In Scripts: Use __version__, pkg_resources, or importlib.metadata.
  3. Edge Cases: Fall back to subprocess calls to pip.

These methods ensure you can reliably check module versions across environments.

Leave a Reply

Your email address will not be published. Required fields are marked *