Juicy lil' bytes

How to Detect Python Version 2 vs 3 in Your Script

Here is a way to build in the logic to deliver separate blocks of Python 2 and 3 code based upon the version of the Python interpreter that the user is running.

The Python sys.version_info Tuple

This technique requires the sys module, so let’s import that first:

import sys

Then use the sys.version_info tuple to determine the version of the Python interpreter:

 if (sys.version_info > (3, 0)):
     # Python 3 code in this block
     import base64
     return base64.b64encode(data).decode()
     # Python 2 code in this block
     return data.encode("base64")

You can use this to build in detection of any major or minor Python release (or development releases if that is required in your project – see below).

Here is the description of the version_info tuple from the Python documentation:

A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is ‘alpha’, ‘beta’, ‘candidate’, or ‘final’. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, ‘final’, 0). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on.