Importing a module based on installed python version?

Though the ImportError approach (SilentGhost's answer) is definitely best for this example, anyone wanting to do that __version__ thing would use something like this:

import sys
if sys.version_info < (2, 6):
    import simplejson as json
else:
    import json

To be absolutely clear though, this is not the "best way" to do what you wanted... it's merely the correct way to do what you were trying to show with __version__.


try:
    import simplejson as json
except ImportError:
    import json

of course, it doesn't work around cases when in python-2.5 you don't have simplejson installed, the same as your example.

Tags:

Python

Json