How can I check for Python version in a program that uses new language features?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The Builders
--
Chapters
00:00 Question
01:45 Accepted answer (Score 118)
02:25 Answer 2 (Score 108)
03:03 Answer 3 (Score 34)
03:27 Answer 4 (Score 22)
03:49 Thank you
--
Full question
https://stackoverflow.com/questions/4460...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #version
#avk47
ACCEPTED ANSWER
Score 118
You can test using eval:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with is available in Python 2.5, just add from __future__ import with_statement.
EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
ANSWER 2
Score 109
Have a wrapper around your program that does the following.
import sys
req_version = (2,5)
cur_version = sys.version_info
if cur_version >= req_version:
import myApp
myApp.run()
else:
print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
ANSWER 3
Score 34
Try
import platform platform.python_version()
Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere.
ANSWER 4
Score 22
Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.
import sys
if sys.hexversion < 0x02060000:
print "yep!"
else:
print "oops!"