Skip to content

Instantly share code, notes, and snippets.

@mplanchard
Created January 23, 2018 14:47
Show Gist options
  • Save mplanchard/88dd24c01aad6f6cfb022e2a4d21e1f4 to your computer and use it in GitHub Desktop.
Save mplanchard/88dd24c01aad6f6cfb022e2a4d21e1f4 to your computer and use it in GitHub Desktop.
Python 2/3 Compatible Version Checking without Third Party Packages
"""This gist describes how to check which version of Python is running.
This one is easy enough that there's really no reason to reach for six's
PY2/PY3 attributes.
"""
from sys import version_info
# verison_info acts like a named tuple of the form
# (major, minor, micro, releaselevel, serial), so standard tuple
# comparisons can be used:
PY2 = version_info < (3,) and >= (2,) # running Python 2.x
PY3 = version_info >= (3,) and < (4,) # Running Python3.x
PY34 = version_info >= (3, 4) and version_info < (3, 5) # running 3.4.x
# You can also access tuple components by name:
PY2 = version_info.major == 2
PY3 = version_info.major == 3
PY34 = version_info.major == 3 and version_info.minor == 4
# Or by index, including slices:
PY2 = version_info[0] == 2
PY3 = version_info[1] == 3
PY34 = version_info[:2] == (3, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment