In order to get around syntax errors you would have to use conditional imports, if you want to mix syntax between versions 2 and 3.
# just psuedocode
if version is x:
import lib_x # contains version x implementation
else:
import lib_y # contains version y compatible implementation
It is not advisable to try to maintain compatibility between python3 and older versions. That said, here are several ways of detecting the version of python being used:
While not particularly human friendly, sys.hexversion
will work across the widest variety of python versions, since it was added back in version 1.5.2:
import sys
if sys.hexversion == 0x20505f0:
print "It's version 2.5.5!"
You should be able to get version information from sys.version_info
(added in python 2.0):
import sys
if sys.version_info[0] == 2:
print "You are using version 2!"
else:
print "You are using version 1, because you would get SyntaxErrors if you were using 3!"
Alternatively you could use the platform module, though that was introduced in python 2.3, and would not be available in older versions (assuming you even care about them):
try:
import platform
if platform.python_version().startswith('2'):
print "You're using python 2.x!"
except ImportError, e:
print "You're using something older than 2.3. Yuck."