Friday Filosofical Finking: Import protections

Chris Angelico rosuav at gmail.com
Wed Apr 17 16:29:07 EDT 2019


On Thu, Apr 18, 2019 at 6:21 AM DL Neil <PythonList at danceswithmice.info> wrote:
>
> (I know it's not Friday [exp], and after personal apologies[apo])
>
>
> Do you bother with exception handling for import statements?
>
>
> Most of the code I read, both in books and during code review, eschews
> any form of ImportError check. Even data science people who 'clean'
> every data field towards inclusion/exclusion in the analysis, take for
> granted that numpy, scipy, pandas, et al, will be available to their code.
>
>
> Does such a check seem un-pythonic? [sto] (maybe 'forgiveness cf
> permission'?)
>
> Can we assume that if such a catastrophic error occurs, it is quite
> acceptable for the code to fall-over in a tumbling-fumble?

I try/except around import statements only if it's possible for the
program to recover from the exception. For instance, something that
runs on Py2 and Py3 might attempt to import from a Py3 name (urllib
comes to mind), and if it fails, redo the import from the Py2 name; or
something might try to import an optional subroutine, and if it isn't
present, set something to None, or to a null function.

For something that is absolutely required for the program to continue,
what would be in your exception handler? Print a message to stderr and
exit? That's exactly what not-catching-the-exception is for. I do
sometimes annotate the imports, though:

from dataclasses import dataclass # ImportError? Upgrade to Python 3.7
or pip install dataclasses

If that bombs out, the entire line will get printed, comment and all,
and there isn't really anything else that I would want to do with the
exception.

So I guess the best way to answer your question is with another
question: If such a catastrophic error occurs, what ELSE would your
code do than fall over? If there's an answer to that question, then
sure, catch the ImportError. Otherwise don't.

ChrisA



More information about the Python-list mailing list