PEP 810: Explicit lazy imports

Definite +1 on the general idea (and I appreciated the explanation of “Why not from mod lazy import name?”)

I also agree on using lazy as the soft keyword - “lazy imports” is the term that actually gets used in practice, so we may as well make it the syntax.

I think the PEP needs to justify this decision, as it’s what rules out using lazy imports for cheap existence checking.

Specifically, @oscarbenjamin’s suggestion of allowing code like:

try:
    lazy import numpy
    using_numpy = True
except ImportError:
    using_numpy = False

For that to be meaningful, the lazy keyword would need to work the same way LazyLoader does (eagerly ensuring the module spec can be found, deferring the actual execution of the module code). If the lazy imports worked that way, the eagerly looked up __spec__ could be made available on the lazy placeholder objects so it didn’t need to be looked up again when the import was reified.

Using those semantics would also potentially open the door to allowing enabling lazy imports globally to affect imports inside try/except statements and context managers, since “import attempt as existence check” would still work. (It’s only “potentially”, as the handling of exceptions raised as a side effect of running the module’s code would still no longer work as written).

While I don’t really mind if the PEP sticks with its current semantics, I do believe it would benefit from a “Why not eagerly look up the import specifications for lazily loaded modules?” section under “Rejected Ideas”.

13 Likes