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.
This technique requires the sys module, so let’s import that first:
Then use the
sys.version_info tuple to determine the version of the Python interpreter:
1 2 3 4 5 6 7
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 is equivalent to sys.version_info.major and so on.