How can I check for Python version in a program that uses new language features? How can I check for Python version in a program that uses new language features? python python

How can I check for Python version in a program that uses new language features?


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 compatibilitytry:  eval("1 if True else 2")except SyntaxError:  raise ImportError("requires ternary support")# import from another modulefrom impl import *


Have a wrapper around your program that does the following.

import sysreq_version = (2,5)cur_version = sys.version_infoif 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.


Try

import platformplatform.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.