Modeling no dependency when testing a python script

What is the best way to temporarily hide an installed module from a python script to check how it handles environments in which the module is not installed?

I would like to avoid removing the module just for verification.

+4
source share
2 answers
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 numpy import attempts now raise ImportError :

 try: import numpy except ImportError as err: print(err) # No module named numpy 

Removing sys.modules['numpy'] allows numpy imported as usual:

 del sys.modules['numpy'] import numpy 
+6
source

Change your Python Path.

The directory order in sys.path shows the search order.

You can change sys.path in the test to change the search order.

+3
source

Source: https://habr.com/ru/post/1344718/


All Articles