Friday Filosofical Finking: Import protections

Grant Edwards grant.b.edwards at gmail.com
Thu Apr 18 09:55:11 EDT 2019


On 2019-04-18, DL Neil <PythonList at DancesWithMice.info> wrote:
> On 18/04/19 8:44 AM, Grant Edwards wrote:
>> On 2019-04-17, DL Neil <PythonList at DancesWithMice.info> wrote:
>> 
>>> Do you bother with exception handling for import statements?
>> 
>> Sometimes.  There are two cases when I do that:
>> 
>>   1. When the module has different names under Python2 and Python3 and
>>      the program tries first one, then the other.
>
> Excellent example - and a lot easier than interrogating os.environ (for 
> example), ie permission cf forgiveness.
>
>
>>   2. When the program can still do something useful (if perhaps
>>      feature-limited) without the imported module by substituting
>>      something else in its place.
>
> Any (publishable) examples?

I can describe one example, but the source doesn't belong to me so I
can't publish it.  I wrote an application that dissects a proprietary
Ethernet protocol and prints out what's going on as a human-readable
transcript.

In the "normal" case, it uses pylibpcap to either capture packets live
or read them from a saved capture file.  If the import of pylibpcap
fails, I replace it with a built-in class which can only read packets
from a one particular type/version of capture file.  If you try to do
a live capture with the built-in class (or read an unsupported capture
file format), it prints an error message saying that's only possible
with pylibpcap and exits.

I can recall one or two other similar cases where a built-in class
handles a limited set of the functionality provided by the missing
module, but they're too obscure to describe succinctly...

>> You've omitted the second thing assumed by the authors: without numpy,
>> scipy, pandas, et alia the program can do nothing useful.
>
> but... what of the third inherent assumption: that the user(s) will be 
> able to handle the situation (discussed in another msg 'here')?

Or they notify somebody who can.  The probability of being able to
programmatically download and properly install a missing module in
order to automagically recover from a failed import is, in practice,
zero.  You could try to format the error in a prettier way, I suppose,
but that's just going to confuse experienced users and admins, and it
isn't going to help the user who doesn't know what to do anyway.

-- 
Grant Edwards               grant.b.edwards        Yow! Don't hit me!!  I'm in
                                  at               the Twilight Zone!!!
                              gmail.com            




More information about the Python-list mailing list