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.
You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.
The 4 ways to import a moduleImport the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.
This is a bit hacky, but you could check the message on the exception to determine what failed:
try:
from mylibrary.codecs import optional
except ImportError, e:
if e.message != 'No module named optional':
raise
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With