Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Python libraries and gracefully handling if they are not availalble

I would like to import bunch of libraries and catch the exception.

If I have only 1 try catch block I get 1 exception (the first one). Is there a pattern to iterate over all of the libs and have a separate exception for each individual missing lib?

#!/usr/bin/env python

try: import sys
except: print sys.exc_info()
try: import numpy as np
except: print sys.exc_info()
try: import scipy as sp
except: print sys.exc_info()
try: import os as os
except: print sys.exc_info()
try: from operator import itemgetter
except: print sys.exc_info()
try: import socket
except: print sys.exc_info()
try: import logging
except: print sys.exc_info()
try: from time import gmtime, strftime
except: print sys.exc_info()
like image 529
Istvan Avatar asked Nov 26 '13 19:11

Istvan


2 Answers

You can use __import__ to dynamically import modules, allowing you to - among other things - import modules by iterating a list with their names.

For example:

libnames = ['numpy', 'scipy', 'operator']
for libname in libnames:
    try:
        lib = __import__(libname)
    except:
        print sys.exc_info()
    else:
        globals()[libname] = lib

You can either extend that to handle the import ... as ... and from ... import ... forms or just do the assignments later manually, ie.:

np = numpy
sp = scipy
itemgetter = operator.itemgetter
like image 89
Aleksi Torhamo Avatar answered Sep 29 '22 12:09

Aleksi Torhamo


Though common, the following easy design pattern and its variations are discouraged:

  # BAD, hides circular import etc. nested errors 
  try:
       import moolib
  except ImportError:
       raise ImportError("You must install moolib from http://moo.example.com in order to run this app")

Instead use the Python package manager to check if a libray is available:

# GOOD
import pkg_resources

try:
    pkg_resources.get_distribution('plone.dexterity')
except pkg_resources.DistributionNotFound:
    HAS_DEXTERITY = False
else:
    HAS_DEXTERITY = True

More about the topic can be found here

  • http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#about-imports

As the comments above point out, Python standard library modules (stdlib) are always available UNLESS you run Python in an embedded environment with stripped down run-time.

like image 23
Mikko Ohtamaa Avatar answered Sep 29 '22 12:09

Mikko Ohtamaa