PEP 690: Lazy Imports

I have used lazy imports in the past and they work great as long as you know what you’re doing, i.e. you explicitly lazily import a module or package.

However, given that Python is not a side-effect free language, there are too many ways this can break in larger code bases when used globally.

Whether a code base is safe w/r to lazy imports is hard to test and what makes things worse is that the import exceptions can suddenly pop up in code which was not written to handle ImportErrors (or other errors happening as a result of the import).

Instead of making this a global option, I think making it easy to use lazy imports on a case by case basis would be better, something like:

lazy import re

E.g. let’s say one of the functions in your module uses the re module, but all others don’t. In this case, a lazy import of the re module at the top of the module would make sense. Alternatively, you can import the re module just in that function, but that hides away a module dependency, which is not always good style.

By putting the lazy import at the top of the module, everyone reading it will immediately know that the module will be used lazily in that module and can take appropriate precautions when writing code in that module.

You know: explicit is better than implicit…

10 Likes