import importlib.util
HAS_NUMPY = importlib.util.find_spec("numpy") is not None
if HAS_NUMPY:
import numpy as np # pyright: ignore[reportMissingImports]
else:
np = None # User doesn't have numpy installed
......
if HAS_NUMPY:
... np. ....
I would have done this
try:
import numpy as np
except ImportError:
np = None
.......
if np:
.... np. .....
They mean slightly different things. With the first one, it tries first to see if numpy can be found, and then if there are any issues with importing it, they get reported as normal; with the second, if anything goes wrong with importing numpy, it will assume that you don’t have it.
(Small side point: You could retain the HAS_NUMPY constant by setting it to True after the import, and setting it to False in the except clause, so if you’re trying to maintain equivalence, that would be an easy fix.)
So it’s a difference of intention. Do you want to fold all types of failures into “we don’t have numpy”, or do you want to specifically check if numpy’s installed, and then failure to import is still a failure?