How to Check Python Module Version

Manav Narula Feb 02, 2024
  1. Use the __version__ Method to Find the Version of a Module in Python
  2. Use the importlib.metadata Module to Find the Version of a Module in Python
  3. Use the pkg_resources Module to Find the Version of a Module in Python
  4. Use the pip show Command to Find the Version of a Module in Python
How to Check Python Module Version

It is usually recommended to use the pip command to install Python modules. It is because, using the pip command, we can specify the required version of the module which we wish to install.

Modules are updated regularly. New functions and features are added regularly, and some also get deprecated, which may lead to errors if one is not aware of these changes. Thus, it is essential to be in knowledge of what version of the module is installed.

In this tutorial, we will discuss how to check for the version of a module in Python.

Use the __version__ Method to Find the Version of a Module in Python

Usually, most of the modules have the __version__ method associated with them, revealing its version.

For example,

import numpy

print(numpy.__version__)

Output:

1.16.5

However, it is not advisable to use this method. First off, __version__ is a magic method that is usually not meant to be called explicitly. Secondly, not every module has this attribute that can tell its version.

Use the importlib.metadata Module to Find the Version of a Module in Python

In Python v3.8 and above, we have the importlib.metadata module, which has the version() function. This function will return the version of the specified module.

For example,

from importlib_metadata import version

print(version("numpy"))

Output:

1.16.5

We can also use the import_metadata module for older versions of Python.

Use the pkg_resources Module to Find the Version of a Module in Python

Below Python 3.8, we can use the get_distribution.version() method from the pkg_resources module to find a module version. Note that the string that you pass to the get_distribution method should correspond to the PyPI entry.

For example,

import pkg_resources

print(pkg_resources.get_distribution("numpy").version)

Output:

1.16.5

Use the pip show Command to Find the Version of a Module in Python

Alternatively, we can use the pip show command to find out details about a specific package that includes its version.

pip show numpy

Note that pip should be updated for this.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Module