I have two versions of the same Python package. I need from a module in a subpackage in the current version to be able to call a function inside the old version of the package (which copied itself in the past)
Where I am now:
now/
package/
__init__.py
subpackage/
__init__.py
module.py -> "import package.subpackage.... <HERE>"
subpackage2/
...
...
The old version:
past/
package/
__init__.py
subpackage/
__init__.py
module.py -> "import package.subpackage; from . import module2; .... def f(x) ..."
module2.py
subpackage2/
...
...
I need to import in <HERE>
the "old" f
and run it.
Ideally
- the function
f
should live its life inside the old package without knowing anything about the new version of the package - the module in the new package should call it, let it live its life, get the results and then forget altogether about the existence of the old package (so calling "import package.subpackage2" after letting
f
do her thing should run the "new" version) - doing that should not be terribly complex
The underlying idea is to improve reproducibility by saving the code that I used for some task along with the output data, and then being able to run parts of it.
Sadly, I understood this is not a simple task with Python 3, so I am prepared to accept some sort of compromise. I am prepared to accept, for example that after running the old f(x)
the name package
in the "new" code will be bound to the old.
EDIT
I tried in two ways using importlib
. The idea was to create an object mod
and then doing f = getattr(mod, "f")
, but it doesn't work
- Changing
sys.path
to['.../past/package/subpackage']
and then callingimportlib.import_module('package.subpackage.module')
. The problem is that it will load the one in "now" even with the changedsys.path
, probably because the namepackage
is already insys.modules
spec = importlib.util.spec_from_file_location("module", "path..to..past..module.py")) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module)
In that case relative imports (from . import module2.py
) won't work, giving the error "attempted relative import with no known parent package"