}

How to check python version the proper way

Created:

Introduction

In this tutorial we will show you how to check the version of python in many common use cases.

Sometimes you want to check the version of python to raise an exception to tell the user to upgrade, or sometimes you want to check if the python interpreter has dictionary comprehension, etc.

We leave to the reader to read about the future module.

Step 1: Learning about sys.version_info

The sys python module provides information that is helpful to identify the system.

import sys
print(sys.version_info)

The output should be a named tuple like this one:

Out[2]: sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)

The tuple of version_info can be used with positional indexes or with the name:

print(sys.version_info[0])
print(sys.version_info.major)

The code above will return the major version, both of them are equally. The difference is readability of the code when using names.

Step 2: Writing the logic to check the python version

if sys.version_info.major > 3:
    if sys.version_info.minor > 2:
        print('Python 3.2 was detected')
    return 0
else:
    # we hardcoded the 2 in the string since we are sure that major version is <= 2
    print('Python 2.{0} was detected'.format(sys.version_info.minor))
    sys.stderr.write('Error: Your Python version is {0}.{0}. Please install pytthon 3.)\n'.format(sys.version_info.major, sys.version_info.minor))
    sys.exit(-1)

Step 3: Making imports compatible with python 2 and 3

Usually one of the problems with compatibility are imports. On python2 StringIO was imported from the StringIO module, but that was changed to module io on python 3. A common technique is to catch ImportError:

try:
    from StringIO import StringIO
except ImportError:
    # Python 3 StringIO import
    from io import StringIO

Step 4: Making new syntax checks

The previous code example will not work when a new syntax need to be checked. In this case we could try to do a simple check and catch the SyntaxError exception. In the next example we are going to test if Dictionary Comprehension is available.

try:
  eval("{n: True for n in range(5)}")
except SyntaxError:
  raise ImportError("Your Python interpreter does not support Dictionary Comprehension")