How to check the current Python version

By

Learn how to check the current Python version at runtime using the sys module and sys.version_info, comparing the tuple to require 3.7 or higher.

~~~

You can check the version of Python that is running a program, at runtime, using the sys.version_info property from the standard library.

Why would you do this? Maybe your program uses a feature added in a recent Python release, like f-strings or the walrus operator. If someone runs it with an older interpreter, they’d get a confusing syntax error. Checking the version lets you print a clear message instead.

First you need to import the sys module from the standard library:

import sys

Then check the content of the sys.version_info property.

This property returns the Python version as a tuple.

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

You can also access each part by name, like sys.version_info.major for the 3 and sys.version_info.minor for the 9.

Python lets you compare tuples, so you can check for example if the current Python version is 3.7.0 or higher:

sys.version_info >= (3, 7)

This works because tuples compare element by element: first the major version, then the minor.

You can add this check in a conditional then, to quit the program when a Python version is too old:

if sys.version_info < (3, 7):
    print('Please upgrade your Python version to 3.7.0 or higher')
    sys.exit()

Put this at the top of your entry file, so it runs before anything else.

Checking from the terminal

If you just want to know which Python is installed on your machine, you don’t need any code. Ask the interpreter directly:

python3 --version

This prints something like Python 3.9.0. Note that python and python3 can point to different installations on the same machine, so check the one you actually use to run your scripts.

Don’t compare version strings

There’s also sys.version, which returns the version as a string, along with build information. It’s fine for printing, but don’t use it for comparisons.

String comparison goes character by character, and that breaks with two-digit versions:

>>> '3.10' < '3.9'
True

That says 3.10 is older than 3.9, which is wrong. The 1 character sorts before 9, so the string comparison lies to you. This exact bug broke a lot of tools when Python 3.10 came out.

The fix is what we did above: always compare sys.version_info against a tuple of numbers, never version strings.

Tagged: Python · All topics
~~~

Related posts about python: