How I can check a Python module version at runtime?

Python introduces new features with every version. Knowing the current Python version or checking third-party package versions at runtime is essential for compatibility and debugging. Python provides several methods to check version information.

Using the sys Module

The sys module provides the most comprehensive version information ?

import sys
print(sys.version)
3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]

Getting Structured Version Info

For programmatic access to version components ?

import sys
print(sys.version_info)
print(f"Major: {sys.version_info.major}")
print(f"Minor: {sys.version_info.minor}")
print(f"Micro: {sys.version_info.micro}")
sys.version_info(major=3, minor=10, micro=6, releaselevel='final', serial=0)
Major: 3
Minor: 10
Micro: 6

Using platform Module

The platform module offers a cleaner string representation ?

import platform
print(platform.python_version())
print(f"Current Python version is: {platform.python_version()}")
3.10.6
Current Python version is: 3.10.6

Getting Version Components as Tuple

import platform
version_tuple = platform.python_version_tuple()
print(f"Major: {version_tuple[0]}")
print(f"Minor: {version_tuple[1]}")
print(f"Patch: {version_tuple[2]}")
Major: 3
Minor: 10
Patch: 6

Checking Third-Party Package Versions

For installed packages, use importlib.metadata (Python 3.8+) or pkg_resources ?

# Modern approach (Python 3.8+)
from importlib.metadata import version
import sys

print(f"Python version: {sys.version_info.major}.{sys.version_info.minor}")

# Example for checking package version (if installed)
try:
    print(f"requests version: {version('requests')}")
except Exception as e:
    print("requests package not found")
Python version: 3.10
requests package not found

Using pkg_resources (Legacy Method)

import pkg_resources

# Get version of an installed package
try:
    version = pkg_resources.get_distribution("numpy").version
    print(f"NumPy version: {version}")
except pkg_resources.DistributionNotFound:
    print("Package not found")

# Note: Use PyPI package name, not import name
# Example: 'mysql-python' not 'MySQLdb'

Comparison of Methods

Method Use Case Output Format
sys.version Detailed Python info Full version string
sys.version_info Programmatic access Named tuple
platform.python_version() Clean version string Simple version (3.10.6)
importlib.metadata Third-party packages Package version string

Conclusion

Use sys.version_info for version checks in code, platform.python_version() for display purposes, and importlib.metadata.version() for third-party package versions. Choose the method that best fits your specific use case.

Updated on: 2026-03-24T17:06:31+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements