__version__()Method to Find the Version of a Module in Python
importlib.metadataModule to Find the Version of a Module in Python
pkg_resourcesModule to Find the Version of a Module in Python
pip showCommand to Find the Version of a Module in Python
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.
__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.
import numpy print(numpy.__version__)
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.
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.
from importlib_metadata import version print(version('numpy'))
We can also use the
import_metadata module for older versions of Python.
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.
import pkg_resources print(pkg_resources.get_distribution('numpy').version)
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
pip should be updated for this.