Question
When encounter ImportError in python, should I directly raise the error and ask the user to install it, or should I use import chain?
Description
I came across this question when I tried to use lxml package to parse xml file in python.
In its official documentation, it says:
If your code only uses the ElementTree API and does not rely on any functionality that is specific to lxml.etree, you can also use (any part of) the following import chain as a fall-back to the original ElementTree:
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
...
It seems to me that it's a bad idea to import a substitution since:
if you can import another library as a substitution, which may not have all the methods as lxml, then all your script can only based on those available methods in all the packages.
Then it make less sense to import the most powerful package (e.g. lxml here), we could directly import the least functional one, and save a lot codes. Or if we want to use additional methods later, we then should directly raise the ImportError.
However, as answered in Error handling when importing modules , I find this approach seems to be used frequently in python programming:
it's useful to define multi-level functionality based on what library has been imported in runtime.
But it seems to me that, the multi-level functionality can only be achieved by constantly checking whether one library has been imported, which makes the whole codes complicated and ugly.
As a result, I just wondered why people sometimes use such structure, instead of raise the error directly?