Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing an optional 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 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.

like image 650
orlp Avatar asked Jan 16 '12 14:01

orlp


People also ask

How do I import options in Python?

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.

What are the two ways of importing module?

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.


1 Answers

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.

like image 108
glyphobet Avatar answered Sep 28 '22 23:09

glyphobet