Is sys.version_info reliable for Python version checking?

No, sys.version_info is not reliable, but only in the sense that almost everything in Python is overwriteable and because of how modules are singletons if no voodoo is being done. Consider the following example, which has one tiny typo.

# bad_dependency.py
import sys

# is_py3 = sys.version_info >= (3,)
is_py3 = sys.version_info = (3,)

What happens when we import this? Well...nothing good.

# our_module.py
import sys
import bad_dependency

print(sys.version_info)

When we run this, since sys is the same module everywhere and since we've overwritten the information we care about, we actually get the following behavior:

$ python our_module.py
(3,)

Of course by this metric almost none of our code is reliable if our imports have bad enough bugs. What's interesting is that it doesn't have to be our code that causes the problem, and the effects certainly don't need to be malicious.

As to the question of whether problems like this exist by default in some reasonably standard Python installations (e.g., micropython, OSX, etc...), I'm still not sure of the answer.


Yes. sys.version_info is a reliable way to determine Python version.

See Python 3 documentation and Python 2 documentation.

Note: sys.version_info is reliable, but not sys.version:

sys.version

A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module.

If you're worried about bad modules changing the values of sys.version_info or something else, you can force a reload of <module 'sys' (built-in)>:

import sys
sys.version_info = "boo"
print(sys.version_info)  # boo

sys.modules.pop("sys")
import sys  # reloaded
print(sys.version_info)
# Output: sys.version_info(major=3, minor=6, ...