I implemented this context manager for importing modules from arbitrary directories.
Good? Bad? - Keen to get thoughts:
Implementation
import sys
class CustomPath:
def __init__(self, path:str):
self.original_path = sys.path
self.custom_path = path
def __enter__(self):
sys.path.insert(0, self.custom_path)
def __exit__(self, type, value, traceback):
sys.path = self.original_path
Usage
Consider this directory structure:
- project1
|- notebooks/
|- notebook1.ipynb
- project2
- ...
- project5/
|-somefiles/
|- common_utils.py
I can run this in the notebook1.ipynb and it works:
with CustomPath('../../project5/somefiles/'):
from common_utils import connect_to_db