202

In my program I want to import simplejson or json based on OS being Linux or Windows. I take the OS name as input from the user. Now, is it correct to do it with a condition like this?

osys = raw_input("Press l for linux, w for Windows:")
if (osys == "w"):
    import json as simplejson
else:
    import simplejson  
4
  • 37
    Why are you taking the os name as input from the user? Look into the platform module. docs.python.org/library/platform.html platform.platform() or platform.system() should do what you need, rather than having a user have to input something every time the code is run. Commented Aug 16, 2010 at 19:32
  • Related principles: stackoverflow.com/questions/11360858/… Commented May 27, 2019 at 12:26
  • The operating system is not a good reason to choose between json and simplejson. json is in the standard library since 2.6; simplejson is a third-party library. The reasons to look for simplejson are because it's needed (older Python version) or preferred (consciously installed by the user to take advantage of extra functionality). Whether or not simplejson is available, has nothing to do with the operating system. Commented Jan 19, 2023 at 4:08
  • "there is nothing wrong with wanting to know if conditional imports are pythonic." Yes, but there is everything wrong with proposing to condition on something nonsensical, because that invites unrelated answers about figuring out what to condition on. Commented Jan 19, 2023 at 4:09

3 Answers 3

249

I've seen this idiom used a lot, so you don't even have to do OS sniffing:

try:
    import json
except ImportError:
    import simplejson as json
Sign up to request clarification or add additional context in comments.

2 Comments

You should first try to import simplejson as json as it is likely a newer (faster) version of the standard json module.
or ujson for speed
81

To answer the question in your title but not the particular case you provide, it's perfectly correct, tons of packages do this. It's probably better to figure out the OS yourself instead of relying on the user; here's pySerial doing it as an example.

serial/__init__.py

import sys

if sys.platform == 'cli':
    from serial.serialcli import Serial
else:
    import os
    # chose an implementation, depending on os
    if os.name == 'nt':  # sys.platform == 'win32':
        from serial.serialwin32 import Serial
    elif os.name == 'posix':
        from serial.serialposix import Serial, PosixPollSerial, VTIMESerial  # noqa
    elif os.name == 'java':
        from serial.serialjava import Serial
    else:
        raise ImportError(
            "Sorry: no implementation for your platform ('{}') available".format(
                os.name
            )
        )

This should be only used in cases where you're assuming and need a strong guarantee that certain interfaces/features will be there: e.g. a 'file' called /dev/ttyX. In your case: dealing with JSON, there's nothing that is actually OS-specific and you are only checking if the package exists or not. In that case, just try to import it, and fall-back with an except if it fails:

try:
    import some_specific_json_module as json
except ImportError:
    import json

2 Comments

No, it's very incorrect to hardcode OS names to decide whether simplejson or json is available. You're quoting code from inherently OS-specific imports, which is a very different case. See Matt's answer for the correct approach.
@Glenn Maynard: I'd defer to you then; I've never used the json package and was trying to answer the more general "can you do conditional imports of modules" question.
15

It is not advisable to use to bind json or simplejson with OS platform. simplejson is newer and advanced version of json so we should try to import it first.

Based on python version you can try below way to import json or simplejson

import sys
if sys.version_info > (2, 7):
    import simplejson as json
else:
    import json

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.