Any way to include based on Python version

Question:

I need to detect Python version and execute code just for this version.

I want to use one file for each version of Python.

Asked By: user894319twitter

||

Answers:

Use sys.version_info.

import sys
PY3 = sys.version_info[0] == 3
if PY3:
   # execute code for python 3
   import file_you_want_for_py3
else:
   # execute code for python 2
   import file_you_want_for_py2
Answered By: lllrnr101

the best and easiest way is to use tox like python library.

Answered By: nipun

If you’re not sure which version of a module might be available, you can use a try/except:

try:
    import new_shiny_module as module
except ImportError:
    import old_rusty_module as module
Answered By: Dolph
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.