Working to Make Python Lazy

5 days ago (iscinumpy.dev)

> This pattern, for example, can’t be lazy: try: import numpy; except ModuleNotFoundError: ...

Wait, that seems bad. These kinds of modules (especially numba) are often exactly the ones that you want to delay importing. Why not provide a way to check the existence at import time? How are you supposed to handle nonexistence in that case?

  • > The error here will move to the first usage of something from numpy. There is a semi-lazy alternative:

      import importlib.util
    
      if importlib.util.find_spec("numpy") is None:
      ... # whatever you wanted to do if numpy is missing
    
      lazy import numpy

This feature seems really valuable for commandline tools! However this paragraph gave me pause:

> Currently, disabling lazy imports disabled the syntax keyword, which means that you can’t use it for circular imports, type checking, etc.

Imo this is a good thing, laziness shouldn't be semantically important. The ability to force disable laziness while maintaining semantics is important for linting and testing, and more often than not, circular imports are a sign of bad code structure.

This seems like an ugly hack. We really need a way to snapshot a python program after its imports have been loaded, similar to temacs/emacs that's been around for decades, or a similar thing that exists in gforth. Emacs's old unexec scheme became unmaintainable but maybe there are still good alternate ways to do it.

Is there a language with a hybrid laziness approach? similar to "do work only if needed" but if you have ressources, do work most likely to be needed, like lazy anticipating?