This is my file structure:
[mylibrary]
__init__.py
[codecs]
__init__.py < this is the file that we're talking about
optional.py
Now I have this code in the marked __init__.py:
def load_optional_codecs():
try:
from mylibrary.codecs import optional
# do stuff with optional
except ImportError:
pass
There is one problem with this. If the optional module contains an import exception itself it will silently fail. Is there a way to import an optional module without silencing any exception from the module?
This might seem like an obscure scenario, but I have gotten a nasty error because of the silenced exception and I would like to prevent that from happening in the future.
This is a bit hacky, but you could check the message on the exception to determine what failed:
With this code, if importing the optional module fails, it is ignored, but if anything else raises an exception (importing another module, syntax errors, etc), it will get raised.