Last Updated: February 25, 2016
· ysgard

Fallback on module import in Python

Python's standard library is pretty comprehensive, but occasionally you will find yourself using modules not included in it. When this happens, you might want your script to react to whether or not that module is available in a given environment.

For example, say that your script stores its data persistently in a database. By default, you've written your script to use Postgresql (via the psycopg2 module) but if Postgres is not present, you resort to the sqlite3 module present in the Standard library to create a disk-based database instead.

To determine which method to use, you can try to import the psycopg2 module first, and then fallback to the default sqlite3 module if that doesn't work, like so:

import sys, os     # standard modules
    import psycopg2
except ImportError:
    import sqlite3
    PG_AVAILABLE = False

Now you can determine which routine to use by checking whether PG_AVAILABLE is set to true or false.