[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Friday Filosofical Finking: Import protections

Chris Angelico writes:
> Actually, only the Python interpreter has to be able to do those
> steps. That's why I put the comment *on the same line* as the import
> statement (not immediately above it, for instance). It comes out like
> this:
> (env) rosuav at sikorsky:~/shed$ python3 BL2_find_items.py
> Traceback (most recent call last):
>   File "BL2_find_items.py", line 19, in <module>
>     import lzo # ImportError? pip install python-lzo
> ModuleNotFoundError: No module named 'lzo'
> (env) rosuav at sikorsky:~/shed$

Oh, I see: because it prints the full line that caused the exception.

> > for regular users, when you know an error is both likely and unclear
> > to read, it might make sense to catch the exception and print
> > a clearer message.
> Define "clearer", though. Given that many MANY users won't read *any*
> error message, the clarity becomes largely moot, and only a handful of
> people will (a) read what you print out, (b) be able to resolve the
> problem, and (c) not be able to figure it out from four lines of
> output.

When writing programs for general use (which this admittedly wasn't),
it seems sad to accept unclear errors on the assumption that some
users don't read error messages. Even most of the nontechnical
users I know will read a one-line error message, though they
certainly wouldn't try to read a 4-line stack trace. I usually try
to catch errors that I expect will be common, and print something
clearer than the default traceback.

> Indeed. But the biggest argument in favour of this style of thing is
> that it requires almost zero effort and has almost zero code
> readability cost. Imagine having half a dozen dependencies and tagging
> each one with a comment like mine... and now imagine having to bracket
> each one of them with a try/except and an appropriate message.

Certainly. I don't use try/except on imports in general. And I
like your short form, and there are definitely places where I'll use
that now where a try/except would have been overkill.