Ok, I think I figured it out. It seems that in the statement:
from parent_module import unavailable_module
Python is looking for the parent_module attribute called unavailable_module . Therefore, the following installation code completely replaces unavailable_module inside parent_module :
import mock import sys fake_module = mock.MagicMock() sys.modules['parent_module.unavailable_module'] = fake_module setattr(parent_module, 'unavailable_module', fake_module)
I tested four import idioms that I know of:
import parent_module import parent_module.unavailable_module import parent_module.unavailable_module as unavailabe_module from parent_module import unavailable_module
and each of them worked with the above code.
source share