syspathcontext.py 963 B

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