Friday Filosofical Finking: Import protections

Chris Angelico rosuav at gmail.com
Thu Apr 18 12:11:58 EDT 2019


On Fri, Apr 19, 2019 at 1:36 AM Akkana Peck <akkana at shallowsky.com> wrote:
> One example: there are a gazillion whois modules, and when I run my
> domaincheck program on a machine where I haven't yet installed
> whois, it's helpful to have a reminder of which one I should
> install. (Of course, if you have one of the other whois modules
> installed, the program will fail somewhere else.)
>
> try:
>     import whois
>     # python-whois from pypi, not whois from pypi or python-whois from debian
>     # https://bitbucket.org/richardpenman/pywhois
> except ImportError:
>     print("Couldn't import whois. Try: pip3 install python-whois")
>     sys.exit(1)

I write this as:

import whois # ImportError? pip install python-whois

Way easier, AND 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
(not usually significant, but when it is, I'd usually rather the
errors go to stderr).

About the only downside is that it assumes the .py file is available -
this won't work with a .pyc-only setup.

ChrisA



More information about the Python-list mailing list