This probably has an obvious answer, but I'm a beginner. I've got a "module" (really just a file with a bunch of functions I often use) at the beginning of which I import a number of other modules. Because I work on many systems, however, not all modules may be able to load on any particular machine. To make things slightly more difficult, I also change the names of the packages when I import them -- for example, matplotlib gets abbreviated to mp.
What I'd like to do is only load those modules that exist on the system I'm currently using, and do some error handling on the ones that don't. The only way I can think of doing so is by enclosing each import statement inside its own try block, which seems pretty un-pythonic. If I enclose them all in the same try block, whichever module throws an error will prevent the subsequent modules from being loaded. Any ideas that might make things look prettier? It would be so easy if I didn't want to change their names...
The easiest way is to ensure that all modules can be loaded on all systems. If that doesn't work, enclosing each
import
statement in atry
block is the next best solution and not un-Pythonic at all.I don't think
try except
block is un-pythonic; instead it's a common way to handle import on Python.Quoting Dive into Python:
As advocated by https://stackoverflow.com/a/20228312/1587329 [modified]
imports all libraries in
named_libs
. The first string is the library name, the second the shorthand. For unnamed libraries, you can use the original: