1

Is there any standard practice on how a library should behave, when certain module can't be imported? Should it just let an exception fly or should it rather catch it and exit elegantly with a proper information?

For example I have something like this:

try:
   from argparse import ArgumentParser
except ImportError:
   print('fathom library requires python 3.2 or argparse package.')

Is it better or worse?

gruszczy
  • 40,948
  • 31
  • 128
  • 181

3 Answers3

4

A library should always raise an ImportError instead of exiting; the program may want to conditionally include it (perhaps replacing it when it is not available).

If a lower-level module raises ImportError, your best shot is to re-raise it with extra information attached.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Your first paragraph is confusing. In each of 2 cases (A attempts to import B, and A attempts to import B which attempts to import C), please say which is "a library", "the program" and "it". The most plausible interpretation is A==program, B==library, C==it ... but "it" has no referent. – John Machin Apr 11 '11 at 23:47
2

If you can, distribute the module with your package, and then follow this pattern to choose which one you're using (prefer the Python 3.x one, default to your shipped one).

If not, this is generally okay as long as you also make sure this doesn't silently cause a more obscure exception later on (ie, make sure you cleanup at the end of the except and in all likelihood, either re-throw this exception or throw your own).

PS - This wasn't an uncommon occurrence for simplejson before it got included in Python proper as well

Community
  • 1
  • 1
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
0

Its a matter of taste. I like your method though. It's clear and clean.

poy
  • 10,063
  • 9
  • 49
  • 74