command_context.py 817 B

12345678910111213141516171819202122232425262728
  1. from collections.abc import Generator
  2. from contextlib import AbstractContextManager, ExitStack, contextmanager
  3. from typing import TypeVar
  4. _T = TypeVar("_T", covariant=True)
  5. class CommandContextMixIn:
  6. def __init__(self) -> None:
  7. super().__init__()
  8. self._in_main_context = False
  9. self._main_context = ExitStack()
  10. @contextmanager
  11. def main_context(self) -> Generator[None, None, None]:
  12. assert not self._in_main_context
  13. self._in_main_context = True
  14. try:
  15. with self._main_context:
  16. yield
  17. finally:
  18. self._in_main_context = False
  19. def enter_context(self, context_provider: AbstractContextManager[_T]) -> _T:
  20. assert self._in_main_context
  21. return self._main_context.enter_context(context_provider)