I'm trying to support multiple versions of a python package without impacting client code.
Consider the following repo:
.
|-- client_code.py
`-- lib
|-- __init__.py
|-- foo.py
`-- bar/baz.so
client_code.py:
from lib.foo import f
from lib.bar.baz import g
...
f()
g()
I'd like to leave client_code.py unchanged but also have access to both versions of the library. I would ideally like something like this:
lib
|-- __init__.py
|-- v1
| |-- __init__.py
| |-- foo.py
| `-- bar/baz.so
`-- v2
|-- __init__.py
|-- foo.py
`-- bar/baz.so
lib/__init__.py:
import os
if os.environ.get("USE_V2", "0") == "0": # Or some other runtime check
from .v1 import *
else:
from .v2 import *
However, the client code fails with the following error:
Traceback (most recent call last):
File "client_code.py", line 1, in <module>
from lib.foo import f
ImportError: No module named foo
Note that the problem doesn't have to do with __all__ since the following would also fail with the same exception:
if os.environ.get("USE_V2", "0") == "0":
from .v1 import foo
else:
from .v2 import foo
I feel like something like this has to be possible, but I'm having a hard time finding the right keywords to search for, so I'm asking here.
The reason for requiring this (as opposed to just having different runtime environments) is because I would like the library version being used to be user-specified at runtime (e.g., use a specific .so compiled for a given GPU architecture). I could create separate Docker images for all of the permutations, but that would be excessively cumbersome.
A more restricted version of this question was previously asked here (Support two versions of a python package without clients needing to change code). The accepted solution, however, requires a separate "mirror" library where a separate file is required for each module in lib. The sole purpose of which is to redirect to v1 or v2 based on the runtime variable.
Is it possible to have a single redirection point for all submodules nested under lib?
Any help would be much appreciated. Thanks ahead of time!