tags:

views:

82

answers:

2

My module currently imports the json module, which is only available in 2.6. I'd like to make a check against the python version to import simplejson, which can be built for 2.5 (and is the module adopted in 2.6 anyway). Something like:

if __version__ 2.5:
    import simplejson as json
else:
    import json

What's the best way to approach this?

+5  A: 
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.

SilentGhost
might wanna do "import simplejson as json" though... but yeah, much better than checking python version
xyld
fixed before I saw your comment
SilentGhost
+3  A: 

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__.

Peter Hansen
the other way around, simplejson is available in py2.5
SilentGhost
Thanks for the correction... I meant >= and not <. Feel free to delete your comment and mine (or I'll do mine if you can't).
Peter Hansen
if version is higher then (2,6) there is **no** simplejson available!
SilentGhost
Doh! I didn't see that you'd already edited it, and just reversed it without thinking, undoing your change. Changed again, and fixed minor typo.
Peter Hansen