10

有没有办法整理以下代码,而不是一系列嵌套的 try/except 语句?

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!"
4

5 回答 5

7

我在http://mail.python.org/pipermail/python-list/2007-May/441896.html找到了以下函数。它似乎工作得很好,而且我很确定它的导入方式不会影响您可能已经拥有的任何现有导入。

def module_exists(module_name):
    try:
        mod = __import__(module_name)
    except ImportError:
        return False
    else:
        return True

if module_exists('simplejson'):
    import simplejson as json
elif module_exists('json'):
    import json
elif module_exists('django.utils'):
    from django.utils import simplejson as json
else:
    raise ImportError('Requires either simplejson, Python 2.6 or django.utils')

我知道这似乎是更多的代码,但是如果你做了很多这样的事情,这个函数可以在其他地方重用。

于 2008-12-23T07:28:56.887 回答
4
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')
于 2008-12-23T09:45:03.993 回答
1

我很欣赏这样做的漂亮功能,但您在原始问题中说明的模式是此要求最常用的模式。您可以看到它在许多开源项目中使用。

我建议你坚持下去。记住“丑”并不总是“坏”。

于 2008-12-23T10:45:05.743 回答
1

这避免了嵌套,但我不确定它是否更好:)

json = None

if json is None:
    try:
        import json
    except ImportError:
        pass

if json is None:
    try:
        import simplejson as json
    except ImportError:
        pass

if json is None:
    try:
        from django.utils import simplejson as json
    except ImportError:
        pass    

if json is None:
    raise ImportError('Requires either simplejson, Python 2.6 or django.utils')
于 2019-01-24T11:23:34.057 回答
0

我想出了一个不依赖于定义函数的简单替代方案:

# Create a dummy enclosing
while True:
    try:
        import simplejson as json
        break
    except:
        pass

    try:
        import json
        break
    except:
        pass

    try:
        from django.utils import simplejson as json
        break
    except:
        pass

    raise ImportError('Requires either simplejson, Python 2.6 or django.utils')

请注意,我不完全确定它是否比使用辅助函数的方法更漂亮。

于 2015-06-29T12:53:54.047 回答