I am looking for a Python routine that loads and returns a module from a filename, even if a module with that name or from that filename was imported before.
More specifically, I want to write a function unconditional_import
that passes the following tests:
import os
def make_module(folder, filename, version):
try: os.mkdir(folder)
except OSError: pass
f = open(os.path.join(folder,filename), "w")
f.write("version = %i" % version)
f.close()
make_module("test","spam.py", 1)
assert( unconditional_import("test","spam.py").version == 1 )
make_module("test","more_spam.py", 2)
assert( unconditional_import("test","more_spam.py").version == 2 )
make_module("test","more_spam.py", 3)
assert( unconditional_import("test","more_spam.py").version == 3 )
make_module("test2","more_spam.py", 4)
assert( unconditional_import("test2","more_spam.py").version == 4 )
I found a solution for this (which I will post as an answer to keep things structured), but it is rather ugly and does not feel robust. I would expect there to be some easier, native way to do this, but I fail to find it.
Notes:
I am aware of How to import a module given the full path?, which addresses how to import a module from a path, but only works once.
I am aware that in most cases, one would just reload the interpreter, but that’s not an option for me.