I want to try to import a list of JSON parsing libraries in python, with precedence for item in the order of which they're tried. If I have the following json libraries ajson
, bjson
, ... I'd have to write something like
try:
import ajson as json
except ImportError:
try:
import bjson as json
except ImportError:
try:
import cjson as json
except ImportError:
...
which is very unreadable. Is there a better way to do this like an if statement?
You could define a function that encapsulates this fallback behavior:
import importlib
def import_fallback(*modules):
for m in modules:
try:
return importlib.import_module(m)
except ImportError:
continue
raise ImportError("All fallback imports failed: {}".format(modules))
# You can use it like this
json = import_fallback("ajson", "bjson", "cjson")
Edit: There might be a downside from doing this. Some linters or static code analyzers might not know that you are importing these modules by running this function