How I can check a Python module version at runtime?


Python introduces new features with every latest version. Therefore, to check what version is currently being used we need a way to retrieve them. If a user implements features without the correct version, it can generate random issues.

We can check the version using few different methods. These methods are discussed below.

Using the Sys Module

Using sys module, we can retrieve the current python module version. The following lines of code can be used to do so.

import sys
print(sys.version)

Output

The output obtained is as follows.

3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]

Example

Using sys module to retrieve the current python module version

print(sys.version_info)

Output

The output is as follows.

sys.version_info(major=3, minor=8, micro=8, releaselevel='final', serial=0)

Example

Using sys module to find out the current version of the python module.

import sys
print(sys.version_info.major)
print(sys.version_info.minor)
print(sys.version_info.micro)

Output

The output is as follows.

3
10
6

Using Platform module

Using Platform module, we can retrieve the current python module version.

import platform
print(platform.python_version())
print("Current Python version is: "+platform.python_version())

Output

3.8.8
Current Python version is: 3.8.6

Example

In this example, we will see how to print the current version of the module separately instead of as a single input. The working can be seen below.

import platform
print(platform.python_version_tuple()[0])
print(platform.python_version_tuple()[1])
print(platform.python_version_tuple()[2])

Output

The output generated is as follows.

3
8
8

The pkg_resources module

Use pkg_resources module to get the module version at runtime. Anything installed from PyPI at least should have a version number.

import pkg_resources
pkg_resources.get_distribution("blogofile").version

Note that package name must be that of PyPI entry.So something like "pkg_resources.get_distribution('MySQLdb').version" won't workbut "pkg_resources.get_distribution('mysql-python').version" will.

Updated on: 11-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements