18

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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

might wanna do "import simplejson as json" though... but yeah, much better than checking python version
fixed before I saw your comment
22

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

5 Comments

the other way around, simplejson is available in py2.5
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).
if version is higher then (2,6) there is no simplejson available!
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.
would this be the way for determining python 2 vs 3? Some import thats not part of standard library has to be modified for python 3, but its not until a method is used that an error would occur. So in a local file directory there would be something like; pyread2 and pyread3.
2

You can import one or more modules without Handling ImportError error:

import sys

major_version = sys.version_info.major
if major_version == 2:
    import SocketServer
    import SimpleHTTPServer
    import urllib2
elif major_version == 3:
    import http.server as SimpleHTTPServer
    import socketserver as SocketServer
    import urllib.request as urllib2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.