Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating lack of a dependency when testing a python script

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.

like image 525
Acorn Avatar asked Jan 21 '23 04:01

Acorn


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 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
like image 82
unutbu Avatar answered Jan 22 '23 20:01

unutbu


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.

like image 32
S.Lott Avatar answered Jan 22 '23 20:01

S.Lott