Import add-on module

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 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, it will fail. Is there a way to import an add-on module without disconnecting any exceptions from the module?


This may seem like an obscure scenario, but I got an unpleasant error due to the excluded silence of the exception, and I would like to prevent this in the future.

+7
source share
1 answer

This is a bit hacky, but you can check the exception message to determine if it failed:

 try: from mylibrary.codecs import optional except ImportError, e: if e.message != 'No module named optional': raise 

With this code, when importing an additional module fails, it is ignored, but if something else throws an exception (import of another module, syntax errors, etc.), it will be raised.

+7
source

All Articles