Run python -m pip show <package_name> or python -m pip list in the terminal to inspect installed package versions from the command line, or use importlib.metadata.version("<package_name>") (built into Python 3.8+) to query a package’s installed version programmatically at runtime.
Basic Example
# 1. Check the exact version and metadata of a single package in the terminal
python -m pip show requests
# 2. List all installed packages and their versions in the active environment
python -m pip list
# 3. Check a package version programmatically inside Python (Python 3.8+)
from importlib.metadata import version, PackageNotFoundError
try:
print(version("requests")) # Output: "2.32.3"
except PackageNotFoundError:
print("Package is not installed.")
Key Details & Edge Cases
- Why
importlib.metadata.version()beatsmodule.__version__: While many libraries expose amodule.__version__attribute (e.g.,pd.__version__,np.__version__), PEP 396 was deprecated because not every package defines__version__(e.g.,requestshas it, whereasbeautifulsoup4orPyYAMLmay lack or differ on it).importlib.metadata.version()reads the standardized distribution metadata directly fromsite-packagesand works for everypip-installed package without importing the module itself. - Distribution name vs.
importname: Bothpip showandimportlib.metadata.version()expect the PyPI distribution name, not the Python import name (for example, pass"scikit-learn"instead of"sklearn","Pillow"instead of"PIL", and"beautifulsoup4"instead of"bs4"). You can map import names to distribution names dynamically withimportlib.metadata.packages_distributions(). - Check Python’s own version: Use
python --versionin the terminal orimport sys; print(sys.version)inside a script to verify the active interpreter version. - Inspecting outdated packages (
pip list --outdated): Add the--outdatedflag (python -m pip list --outdated) to compare currently installed versions against the latest releases available on PyPI. - Always prefix with
python -m pip: Runningpython -m pip listguarantees you are inspecting the packages installed for that exactpythonexecutable rather than a different global or system Python environment.
Comparison of Version Inspection Methods
| Method | Environment | Works Without Importing Module? | Requires PyPI Distribution Name? | Best Used When |
|---|---|---|---|---|
python -m pip show <pkg> |
Terminal / CLI | Yes | Yes | Inspecting a single package’s version, dependencies, and install path. |
python -m pip list |
Terminal / CLI | Yes | N/A (lists all) | Viewing every installed package and version in the active environment. |
importlib.metadata.version("<pkg>") |
Python code (3.8+) | Yes | Yes | Checking package versions programmatically at runtime without side effects. |
module.__version__ |
Python code | No (must import first) | No (uses imported module) | Quick interactive debugging in a REPL or Jupyter notebook. |
You must log in or register to comment.
