Wednesday, August 21, 2013

One way to safe guard imports of external libraries

Say you have some code that is dependent on some 3rd party library, for instance users can download FragIt that requires Open Babel, but what happens if the user 'forgot' to install Open Babel or configure the paths correctly? Importing FragIt under these circumstances will crash your application because it has some explicit import statements to Open Babel. What should you do as a developer to safe guard this behavior?

The best way to deal with the issue (and this it not just the case of using FragIt, but any kind of library) which I learned from the very excellent "The Clean Coder" by Robert C. Martin is to write a wrapper for the FragIt API to suit your specific needs because this you can unit test and know instantly when the API has changed.

In header of this wrapper, you can provide code that looks like

# always assume that we have openbabel
has_openbabel = True
try:
import openbabel
except ImportError:
has_openbabel = False
def FragIt_GetFragmentationPoints(input):
""" Obtains the fragmentation points using the FragIt API
based on the inpu
"""
# If the user has no Open Babel installed, inform the user
if not has_openbabel:
def FragIt_GetFragmentationPoints(input):
print "WARNING: FragIt API not available because"
print " Open Babel is missing / misconfigured."
return None
view raw safeguard.py hosted with ❤ by GitHub
where we have defined a wrapper to the API to return the fragmentation points we want. However, if Open Babel is not defined, we overwrite that function, letting the user know that something is not right.

There are many ways to deal with it, this is one.

By the way: happy 1 year anniversary for the last blog post!