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 impo
As advocated by https://stackoverflow.com/a/20228312/1587329 [modified, with an edit from @Ian]
from importlib import import_module
named_libs = [('numpy', 'np'), ('matplotlib', 'mp')] # (library_name, shorthand)
for (name, short) in named_libs:
try:
lib = import_module(name)
except:
print sys.exc_info()
else:
globals()[short] = lib
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:
from importlib import import_module libnames = ['numpy', 'scipy', 'operator'] for libname in libnames: try: lib = import_module(libname) except: print sys.exc_info() else: globals()[libname] = lib