3

I am currently writing some code on python 3.3. Unfortunately some of the plugins I rely on are not yet compatible with Python3 and I need to switch back to Python2.7.

In order to avoid refactoring all the code, I would like to do something like

if(os.python.version<3.0):
from _future_ import print, super

What is the proper way of doing this

chiffa
  • 2,026
  • 3
  • 26
  • 41
  • 3
    http://stackoverflow.com/questions/446052/python-best-way-to-check-for-python-version-in-a-program-that-uses-new-language – The Internet Dec 17 '13 at 02:22
  • You can use `from __future__ import print_function` unconditionally, but very many changes do not have an easy future import to resolve them. Porting your program will require more work than that. – user2357112 Dec 17 '13 at 02:30

2 Answers2

4

You're on the wrong track here, on several counts. First, don't check for versions, check for features. The link @dave you in his comment does a good job of explaining that.

Second, if you did check for versions, and even if there weren't multiple spelling errors, this wouldn't work at all:

if(os.python.version<3.0):
    from _future_ import print, super

A __future__ statement can be preceded only by the module docstring, blank lines, comment lines, and other __future__ statements. It cannot appear anywhere else - you'll just get a syntax error if you try.

Third, for the example you gave, checking anything is pointless. Near the top of the file,

from __future__ import print_function

is fine in both Python 2.7 and Python 3. In Python 3 it simply has no effect.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
2

As zhangyangyu says, you can you sys.version_info to get current python version.

sys.version_info is tuple, I always use the first three element in version comparison like this:

if sys.version_info[:3] > (3,0):
    do something
elif sys.version_info[:3] > (2,5,2):
    do something else

Or, you can use distutils.version to compare current version with specified version.

Here is answer about how to use distutils.version.

Community
  • 1
  • 1
WKPlus
  • 6,955
  • 2
  • 35
  • 53