Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load python module not from a file

I've got some python code in a library that attempts to load a simple value from a module that will exist for the applications that use this library

from somemodule import simplevalue

Normally, the application that uses the library will have the module file and everything works fine. However, in the unit tests for this library the module does not exist. I know that I can create a temporary file and add that file to my path at runtime, but I was curious if there is a way in python to load something in to memory that would allow the above import to work.

This is more of a curiosity, saying "add the module to your test path" is not helpful :P

like image 944
smullins Avatar asked Feb 10 '26 16:02

smullins


1 Answers

It is. Use types.ModuleType to create a new module object, then add it to sys.modules:

sys.modules["somename"] = types.ModuleType("somename")

You can then do import somename. If you need to add classes or functions to it, import it before calling your test script, and just add functions to it:

def myfunc(x, y, z):
    ...

somename.myfunc = myfunc

It should go without saying, but just in case: this is largely an academic curiosity. It has some uses for testing, but other than that, stick to importing things the usual way.

Incidentally, how I know about this: I've come across the technique used in testing, to make a "stub" for the _winreg module on non-Windows systems. Here it is in use.

like image 139
Thomas K Avatar answered Feb 12 '26 15:02

Thomas K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!