I need to use a modified version of a library modul containing a class. For my understanding the best practice for this is to create a local copy (with identical file- and classname) of said module in my own source folder, modify it and import the local version instead of the version from the library. So the folder structure is
/src/myscript.py
/src/module.py
/some/other/path/library/module.py
It works to import the local version of module in myscript.py with
from module import TheClass
It gets also executed. But for some reason later the class from the library module gets executed as well! So obviously there is a reimport happening in some of the other library code that im working with, that still refers to the library module.
How can I force python to always use the already imported local module.py, when a later import command elsewhere refers to the same module/classname?
Edit1: With myscript.py changed to
import sys
import importlib.util
spec = importlib.util.spec_from_file_location("module.TheClass", "module.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["library.subpack.module"] = foo
[...]
a later import DOES get redirected to the local module.py, but unfortunately this Codeline
[...]
from library.subpack.module import TheClass
[...]
then throws the error:
ImportError: cannot import name 'TheClass' from 'module.TheClass' (module.py)
What module.py looks like (all versions):
import math
__all__ = ["TheClass"]
class TheClass(NestedObject):
[...]