I need to use a utility function that exists in an external module I do not control. The module has many imports that are not used by the specific function I care about. I don't want to install those unnecessary dependencies (and especially not bloat my packages dependency list with the module).
It doesn't seem possible to use the function without the imports. I wondered if it's possible to mock the module? I had briefly hoped this would work:
""" module_a """
import unused_module
def f():
return something_of_value
""" module_b: needs to use module_a.f() but doesn't have unused_import installed. """
import mock_module as unused_module
global unused_module
import module_a
module_a.f()
But I couldn't inject unused_module
into the modules setup. Is there a workaround I could use here?
CodePudding user response:
What about this? We're exploiting the module caching system, where modules only get imported once and get stored in sys.modules
which is a dict.
utili.py (which I should have called module_a.py
)
""" module_a """
import unused_module
def f():
return "something_of_value"
Then the client code that needs to use your function.
user.py
import sys
#we're not really doing anything here, just
#slotting in a fake entry into sys.modules
#so that it wont bother to "reimport" unused_modules
sys.modules["unused_module"] = 1
from utili import f
print(f"{f()=}")
output of executing user.py:
python user.py
f()='something_of_value'
And, to be clear, I don't have an actual unused_module
anywhere, so the import will fail if utili.py
is called first.
py utili.py
Traceback (most recent call last):
File "/Users/myuser/explore/test_384_mockmo/utili.py", line 2, in <module>
import unused_module
ModuleNotFoundError: No module named 'unused_module'
Things will also not go well if any code tries to use unused_module
so your f
definitely can't require its actual existence. Ditto for any code that gets executed at the module load of utili.py
. You could however assign a mock of some sorts instead of the litteral 1
.