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

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!

3 comments:

  1. FYI, I usually use "except ImportError:...openbabel = False". No need for a new variable.

    Happy 1st anniversary!

    ReplyDelete
    Replies
    1. Hey Noel,

      thanks :)

      I'll tinker with your suggestion after digesting the implications of implicit typing in Python.

      Delete
  2. (or actually, openbabel = None...this avoids changing the type too much)

    ReplyDelete