I need to make a module that is not in sys.path
available to the user. I would like to avoid polluting sys.path
with the parent directory of the module to the path, because I don't know what other modules might be there on the user system. Is there a solution that unlike the example below avoids adding the parent directory to the path?
# My library code
import sys
sys.path.insert(0, 'path/to/parent/dir')
import my_module
del sys.path[0]
sys.modules['my_module'] = my_module
# User code
import my_module
Similar questions are available on StackOverflow but don't provide a solution as far as I'm aware:
- Import arbitrary python source file. (Python 3.3+) This seems to only work for single files, not modules that are directories.
- How to import module from parent directory without sys.path? This suggests modifying the Python import path.