Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional import of modules in Python

Tags:

python

People also ask

Can you import in an if statement Python?

Yes. As Martijin's answer pointed out that Official Python use this.

What are the import modules in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


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

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

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