Friday Filosofical Finking: Import protections

MRAB python at mrabarnett.plus.com
Wed Apr 17 16:45:05 EDT 2019


On 2019-04-17 21:20, DL Neil 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?
> 
> Does it make a difference if operating in/out of a dev-ops environment?
> 
> Might such only occur once, because once the environment has been
> correctly-built, it will/can *never* happen again?
> 
> Can we assume Built-in and PSL modules *must* be present, so we only
> need to talk about covering in-house code and pip-ed (or similar) modules?
> 
> Is it more/less important in __main__ than in an imported module?
> 
> Do you handle each import separately, or all in a single try..except block?
> 
> Do you try to anticipate and cover every import in the system at the top
> of __main__, eg imports inside imported modules?
> 
> What about OpSys-specific imports (etc)?
> 
> Do modules import-ed only in specific situations, deserve more, or less,
> attention?
> 
[snip]
Catch only what you (well, the script) can fix.

If it needs numpy, but can't import numpy, then when can it do? Might as 
well just let it fail.

I suppose an alternative might be to try to download and install numpy 
and then retry, but what if it can't be downloaded, or the installation 
fails?

No, you have to give up at some point. It's better just to report the 
problem and leave it to the user to fix it.


More information about the Python-list mailing list