Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidier way of trying to import a module from multiple locations?

Is there a way to tidy-up the following code, rather than a series of nested try/except statements?

try:
    import simplejson as json
except ImportError:
    try:
        import json
    except ImportError:
        try:
            from django.utils import simplejson as json
        except:
            raise "Requires either simplejson, Python 2.6 or django.utils!"
like image 634
dbr Avatar asked Dec 23 '08 04:12

dbr


1 Answers

def import_any(*mod_list):
    res = None
    for mod in mod_list:
        try:
            res = __import__(mod)
            return res
        except ImportError:
            pass
    raise ImportError("Requires one of " + ', '.join(mod_list))

json = import_any('simplejson', 'json', 'django.utils.simplejson')
like image 95
zakhar Avatar answered Nov 15 '22 13:11

zakhar