DEV Community

Tony Colston
Tony Colston

Posted on

detecting Python version in a script

Recently I needed to know if a program I was running was using Python2 or Python3.

There are a couple of ways to do this inside the Python interpreter.

The most obscure way (IMO) is probably the most reliable

import sys
major_version = sys.version_info[0]
print(major_version)
Enter fullscreen mode Exit fullscreen mode

This method is reliable but how did I know to look at position 0 in sys.version_info? That looks odd and feels like magic.

In Python 2.6 sys.version_info was a tuple. It was not a class so sys.version_info[0] is the major number (aka 2). In Python 2.7 and up the sys.version_info became effectively a class and this type of code became valid

print(sys.version_info.major)
Enter fullscreen mode Exit fullscreen mode

That code above will fail in an older Python so the safe way to check your version is the ugly way :(

Top comments (0)