This was my scenario: I have a python library cloned in a git submodule which has a dash in its name:
|- python-my-lib
| `- mylib.py
`- my-script.py
It took me a long time to figure out the equivalent of:
# Do NOT use this!
sys.path.insert(1, './my-lib')
from mylib import MyClass
Appending the path is not an option, as it would only work if you run the script within the same directory. If you do /home/user/bin/my-script.py
, this will fail.
This is the solution:
import importlib
mylib_module = importlib.import_module("python-my-lib.mylib")
MyClass = mylib_module.MyClass
Feel free to further improve this solution, if you know a simpler solution.