dbr*_*dbr 10 python refactoring python-import
有没有办法整理下面的代码,而不是一系列嵌套的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!"
Run Code Online (Sandbox Code Playgroud)
我在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')
Run Code Online (Sandbox Code Playgroud)
我知道这看起来像是更多的代码,但是如果你做了很多这样的话,这个函数可以在其他地方重用.