Explain Codes LogoExplain Codes Logo

How do I detect the Python version at runtime?

python
python-version
version-control
python-3
Anton ShumikhinbyAnton Shumikhin·Sep 15, 2024
TLDR

Detect the Python version during runtime with the sys.version_info in Python.

import sys version = "{}.{}".format(sys.version_info.major, sys.version_info.minor) print("Running Python version", version)

This prints the major and minor Python version, making it clear what Python environment your code is running in.

Control flow for specific Python versions

If you're coding in a way that is dependent on the Python version, you might want to use control flow to handle different versions:

import sys if sys.version_info.major == 3: print("Python 3 code here") elif sys.version_info.major == 2: print("Python 2? You're a time traveler!")

In the example above, we're detecting whether the Python version is 2.x or 3.x and then executing specific code based on that.

Full version details with sys.version

To get the full version string - including the build and compiler information - use sys.version:

import sys # Well, this will be a mouthful... print(sys.version)

Alternative version detection: platform module

The platform module can also give you your Python version. It's like asking a friend to tell you which Python version you are using! Let's check out how to use it:

import platform print(platform.python_version())

Incompatible Python versions: Raise the alarm!

A good practice is to raise an exception if an incompatible Python version is detected. This is like sending an alarm signal when you see an unexpected Python version:

import sys if sys.version_info < (3, 5): raise Exception("Python 3.5 or later required, update your Python version!")

Advanced Python version controls

Syntax variance between Python versions

To accommodate different syntax between Python versions, you can use conditional imports and version-specific functions:

# Python 3 contextlib.redirect_stdout doesn't exist in Python 2 try: from contextlib import redirect_stdout except ImportError: # Do some Python 2 magic to replicate functionality!

Version specific dependencies for third-party libraries

When dealing with third-party libraries, use conditional dependencies in your setup scripts:

from setuptools import setup setup( install_requires=[ 'library>=2,<3' if sys.version_info < (3, 0) else 'library>=3,<4' ] )

This is the equivalent of saying, "library version 2 for Python 2 and library version 3 for Python 3, please!".

Enforcing version in scripts with shebang

The shebang line can specify the required Python version for a standalone script:

#!/usr/bin/env python3

Programmatic version comparison

Use the sys.version_info tuple for complex version comparison. It's like playing "who's older" in a nicer way:

import sys min_version = (3, 5) current_version = sys.version_info[:3] if current_version >= min_version: print("Great, your Python version is up to date!") else: print("Oops, your Python version is a bit old!")

Using hexversion for quick version comparison

The sys.hexversion provides a quick way for version comparison:

import sys # Python 3 check, talk about making things complicated for fun! if sys.hexversion >= 0x03000000: print("Cool, running on Python 3 or later!")