When dealing with JSON objects in Python, we have the excellent simplejson module to convert a JSON object into Python object. But, in Python 2.6 (and 3.0), we have the json. While loading it’s as simple as
try: # Python 2.6/3.0 JSON parser import json except ImportError: # Fallback to SimpleJSON import simplejson as json
And you would just need to use json.dump(), that leaves the problem of pointing if the application requires simplejson or not in the setup.py. The solution is use sys.version_info comparing versions with distutils.version.StrictVersion:
from distutils.version import StrictVersion import sys version_number = '.'.join([str(a) for a in sys.version_info[:3]]) if StrictVersion(version_number) < StrictVersion('2.6'): params['requires'] = ['simplejson']
- First of all, params is a dictionary of parameters passed to setup (as setup(**params), as Python supports passing a dictionary as a list of parameters as a function.) Another probable solution would be use a requires variable and set it to None in case the version is superior than 2.6.
- The version_number uses just the first three elements in sys.version_info 'cause it also contains other information like "final" or "rc" and the release info (e.g., Python 2.5rc1 would have a sys.version_info of (2, 5, 0, 'rc', 1))
- StrictVersion provides proper comparison between versions, so you don't have to worry about Major, Minor and Release versions or even have to write three cases in an if.