interpreter_shutdown.py 1.2 KB

12345678910111213141516171819202122232425
  1. """Shared interpreter-shutdown predicate for background threads that can outlive
  2. process teardown (cron delivery, concurrent tool submission, retry paths).
  3. Once finalization starts, ``concurrent.futures`` refuses new work and asyncio's
  4. default executor is gone, so any further scheduling only produces noise (stray
  5. prints after the TUI exited, tracebacks in ``errors.log``, futile retries).
  6. CPython raises ``cannot schedule new futures after interpreter shutdown``
  7. (module-global flag) or ``... after shutdown`` (a pool whose ``shutdown()`` ran);
  8. the short prefix catches both — safe here because every pool involved is a
  9. module-global daemon or a ``with``-scoped local only finalization can shut down.
  10. """
  11. from __future__ import annotations
  12. import sys
  13. from typing import Optional
  14. def interpreter_shutting_down(exc: Optional[BaseException] = None) -> bool:
  15. """True when the interpreter is finalizing. ``exc`` lets a caller treat an
  16. already-raised scheduling error as a shutdown signal: the ``concurrent.futures``
  17. flag can be set a hair before ``sys.is_finalizing()`` flips."""
  18. if sys.is_finalizing():
  19. return True
  20. return exc is not None and "cannot schedule new futures" in str(exc).lower()