How to find out the version of a Python module ?

Published: April 24, 2023

Tags: Python;

DMCA.com Protection Status

If you want to find out the version of a Python module, there are several ways you can do it. Examples:

Checking the version of a Python module within my code

Using .version

The easiest way is to use the __version__ attribute of the module. For example, to find the version of the matplotlib module:

import matplotlib

print(matplotlib.__version__)

Prints the version of Requests package, e.g.

3.4.3

Using pkg_resources

Another option is to use the pkg_resources module from the setuptools library. This method works if you have installed the module with pip or setup.py. The pkg_resources.get_distribution() function can be used to get a Distribution object for your package, which has a version attribute that contains the version information:

import pkg_resources

dist = pkg_resources.get_distribution('matplotlib')

print(dist.version)

Prints the version of Requests package, e.g.

3.4.3

Checking the version of a Python module not using my code

Another way to confirm the version of the module is to use a Linux command.

Using conda list

If Anaconda is installed and working, this will display a list of installed packages and their versions:

conda list

will print for example

.
.
.
lz4                       3.1.3            py39h9ed2024_0  
lz4-c                     1.9.3                h23ab428_1  
lzo                       2.10                 haf1e3a3_2  
markdown                  3.3.4            py39hecd8cb5_0  
markupsafe                2.0.1            py39h9ed2024_0  
matplotlib                3.5.2            py39hecd8cb5_0  
matplotlib-base           3.5.2            py39hfb0c5b7_0  
matplotlib-inline         0.1.6            py39hecd8cb5_0  
mccabe                    0.7.0              pyhd3eb1b0_0  
mistune                   0.8.4           py39h9ed2024_1000  
.
.
.

Reminder to activate the environment that you wish to check the module version for!

Checking init.py file

Finally, you can locate and read the module's __init__.py file to find the version information. This method is more manual, but it will work even if you haven't installed the module with pip or setup.py. The exact location of the __init__.py file may vary depending on your Python environment, but the general format should be:

Once you open `init.py file, search for the line containing the version information.

References

Links Site
pkg_resources setuptools.pypa.io
version packaging.python.org