| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import sys |
| 4 |
from types import TracebackType |
| 5 |
from typing import Literal, Self |
| 6 |
|
| 7 |
import warnings |
| 8 |
|
| 9 |
|
| 10 |
class prepended_to_syspath: |
| 11 |
"""A context for prepending a directory to sys.path for a second.""" |
| 12 |
|
| 13 |
dir: str |
| 14 |
added: bool |
| 15 |
|
| 16 |
def __init__(self, dir: str) -> None: |
| 17 |
self.dir = dir |
| 18 |
self.added = False |
| 19 |
|
| 20 |
def __enter__(self) -> Self: |
| 21 |
if self.dir not in sys.path: |
| 22 |
sys.path.insert(0, self.dir) |
| 23 |
self.added = True |
| 24 |
else: |
| 25 |
self.added = False |
| 26 |
return self |
| 27 |
|
| 28 |
def __exit__( |
| 29 |
self, |
| 30 |
exc_type: type[BaseException] | None, |
| 31 |
exc_val: BaseException | None, |
| 32 |
exc_tb: TracebackType | None, |
| 33 |
) -> Literal[False]: |
| 34 |
if self.added: |
| 35 |
try: |
| 36 |
sys.path.remove(self.dir) |
| 37 |
except ValueError: |
| 38 |
pass |
| 39 |
# Returning False causes any exceptions to be re-raised. |
| 40 |
return False |