from contextlib import contextmanager

@contextmanager
def add_to_path(p):
    import sys
old_path = sys.path
old_modules = sys.modules
sys.modules = old_modules.copy()
sys.path = sys.path[:]
sys.path.insert(0, p)
try:
    yield
finally:
    sys.path = old_path
sys.modules = old_modules
Python 3.5+: How to dynamically import a module given the full file path (in the presence of implicit sibling imports)?