Friday Filosofical Finking: Import protections

Chris Angelico rosuav at gmail.com
Thu Apr 18 01:32:57 EDT 2019


On Thu, Apr 18, 2019 at 2:32 PM DL Neil <PythonList at danceswithmice.info> wrote:
>
> On 18/04/19 8:29 AM, Chris Angelico wrote:
> > On Thu, Apr 18, 2019 at 6:21 AM DL Neil <PythonList at danceswithmice.info> wrote:
> >> Do you bother with exception handling for import statements?
> >> 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
> ...
>
> User reactions have been covered elsewhere 'here'.

You've given an example of how a user might respond to the exception
traceback. But can you actually offer anything that your program could
do that's BETTER than a traceback? If not, what's the point in
catching the exception?

> > 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:
>
> We disagree. Although I hasten to add, if the error is trapped, then
> there should be some added-value over what is system-provided.
>
> Application's log? SysLog? Particularly in a centralised or server-based
> application especially web-services.

Or, you could stick with stderr, which means that the message will go
whereever the message ought to be sent. If you're running a web
service, you should be catching stderr and putting it somewhere.

> > 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.
>
> Kudos! To whom are you addressing such annotations?
>

Whoever might be running the script. I don't particularly discriminate :)

ChrisA



More information about the Python-list mailing list