PEP 810: Explicit lazy imports

This would work, I think:

import importlib.util

if importlib.util.find_spec("numpy") is not None:
    lazy import numpy
    using_numpy = True
else:
    using_numpy = False

It’s not perfect, but I personally find it difficult to imagine this lazy import syntax intentionally doing any filesystem access during the import statement (at least, I’d prefer it doesn’t).

4 Likes