PEP 810: Explicit lazy imports

But the issue here isn’t performance. The author of some library will move the import opt_dependency from inside the function to a top level lazy import (as is suggested by the PEP). The consequence of this action isn’t that autocomplete now runs slowly, it’s that autocomplete stops working, because dir(somemodule) now always raises an ImportError unless opt_dependency is installed.

How about a third option: do reify on explicit __dict__ access, but special case dir and getattr not to use __dict__ directly (dir wouldn’t reify anything and getattr would only reify the accessed key).

Or even a fourth option: provide a way to lazy import with a default value. For example:

lazy import numpy as np or None
lazy from opt_dependency import expensive_func or default_impl

In this case, reification would attempt to do the normal import, but use the provided default in case of an Exception, instead of propagating it.

3 Likes