Search code examples
pythonpython-3.xpython-2.7python-importtry-except

Run individual python import statements which are stored in a list


I have a list of libraries i'd like to import, but some of them may not be in the filesystem.

Basically, i want to do something like this:

list_of_imports = ['from path1.path2.path3 import x', 'from path1.path2.path4 import y', 'from path1.path2.path3 import z', 'from path1.path2.path2 import a']

for statement in list_of_imports:
    try:
        execute statement
    except:
        ignore error and import the next statement

The reason i want to do this, is because some of the libraries in the list may not be in the filesystem, and i don't want one failure to make the entire file to throw an import error.

How do i do this?


Solution

  • You can try like this:

    list_of_imports = ['from path1.path2.path3 import x', 'from path1.path2.path4 import y', 'from path1.path2.path3 import z', 'from path1.path2.path2 import a']
    
    for statement in list_of_imports:
        try:
            exec(statement)
        except ImportError as e:
            continue
    

    Explanation:

    Iterating over each element from the list using exec() you can execute those import statements. So if there is no error it will import that modules