[Python-ideas] lazy use for optional import

Nicolas Cellier contact at nicolas-cellier.net
Tue Feb 28 18:31:19 EST 2017

I have seen some interest into lazy functionality implementation.

I wondered if it can be linked with optional import.

PEP 8 <http://www.python.org/dev/peps/pep-0008/> authoritatively states:

Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.

So, if we want to stick to PEP8 with non mandatory import, we have to catch
the import errors, or jail the class or function using extra functionnality.

Why not using the potential lazy keyword to have a nice way to deal with it?

For example:

lazy import pylab as pl  # do nothing for now
> # do stuff
> def plot(*args):
>     pl.figure() # Will raise an ImportError at this point
>     pl.plot(...)

That way, our library will raise an ImportError only on plot func usage
with an explicit traceback : if matplotlib is not installed, we will have
the line where it is used for the first time and we will have the name of
the faulty library.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170301/44b1582f/attachment.html>

More information about the Python-ideas mailing list