osdir.com


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

Friday Filosofical Finking: Import protections


On Fri, Apr 19, 2019 at 2:46 AM Akkana Peck <akkana at shallowsky.com> wrote:
>
> Chris Angelico writes:
> > I write this as:
> >
> > import whois # ImportError? pip install python-whois
> [ ... ]
> > it means that normal exception handling is still
> > happening (which might be important if I import this into something
> > else), plus it's printing the message to stderr rather than stdout
> [ ... ]
> > About the only downside is that it assumes the .py file is available -
> > this won't work with a .pyc-only setup.
>
> It also assumes the user is capable of (1) finding the .py file
> (maybe not so easy if it's imported from another program) and
> (2) knowing Python well enough to find and understand the line with
> the comment.

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$

> Which in my example is not a problem since I'm probably
> the only user of my domaincheck script; but when writing programs
> 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.

> Your counterarguments are quite valid, though. It's a trade-off.

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.

ChrisA