Friday, September 26, 2008

Python version check

Just use sys.hexversion instead of the string equivalent (sys.version, sys.version_info, ...). It's flexible and fast.

>>> import sys
>>> sys.hexversion
33882608
>>> hex(sys.hexversion)
'0x20501f0'
>>> if sys.hexversion >= 0x2050100:
...   print "Python 2.5.1 or higher"
... 
Python 2.5.1 or higher

For example, the explicit relative imports is introduced in Python 2.5, you can check this function as:

HAS_RELATIVE_IMPORTS = (sys.hexversion >= 0x2050000)

NOTE: sys.hexversion is available since 1.5.2. It's not worth to support older versions.

0 comments: