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?
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?
import importlib.util
if importlib.util.find_spec("numpy") is None:
... # whatever you wanted to do if numpy is missing
lazy import numpySeriously: crash if your dependencies aren't available. There are better ways to do optional dependencies. ImportError ain't it.
I might recommend doing something like importing from something like `numpy.version` (or some other "random" very small utils package) so that the work done on file load is still fairly small.
What would that be for numba?
For example, numba._version only imports standard library stuff so is probably good enough here[0]
It would be nice to have general querying capabilities here, of course. I just think that in practice there's at least a halfway-decent workaround in almost any real situation
[0] https://github.com/numba/numba/blob/main/numba/_version.py
"Oh you don't have optional dependency? Then do X" needs to happen at runtime right?
In my preference order: an explicit CLI option/envvar which requires the optional dep, a flag file on the filesystem, or an ImportError attempt if you absolutely must. Use a stub/trampoline file in the conditionals so that static analyzers and laziness analysis on that file itself still work.
Also, you need something that works for simple one-file scripts, not just a whole package or project.
If you need something for one-off scripts, use https://docs.astral.sh/uv/guides/scripts/.