What's the best way to temporarily hide an installed module from a python script to test how it handles environments that don't have the module installed?
I'd like to avoid having to uninstall the module just to test.
import sys
sys.modules['numpy']=None
Setting sys.modules['numpy']=None
makes Python think that it has already tried and failed to import numpy
. Subsequent attempts at importing numpy
now raise ImportError
:
try:
import numpy
except ImportError as err:
print(err)
# No module named numpy
Deleting sys.modules['numpy']
allows numpy
to be imported as normal:
del sys.modules['numpy']
import numpy
Change your Python Path.
The order of directories in sys.path
shows the order of a search.
You can change sys.path
in a test to alter the search order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With