# A lightweight cooperative timeout mechanism for synchronous code \`with timeout(seconds):\`

**URL:** <https://discuss.python.org/t/a-lightweight-cooperative-timeout-mechanism-for-synchronous-code-with-timeout-seconds/107811>\
**Category:** Ideas\
**Created:** [June 19, 2026, 4:50am UTC](https://discuss.python.org/t/a-lightweight-cooperative-timeout-mechanism-for-synchronous-code-with-timeout-seconds/107811 "2026-06-19T04:50:02Z")\
**Posts on this page:** 1\
**Showing post:** 19

<div class="post-metadata">

**Author:** ![tstefan](https://avatars.discourse-cdn.com/v4/letter/t/f475e1/32.png) [@tstefan](https://discuss.python.org/u/tstefan)\
**Post date:** [June 23, 2026, 4:06pm UTC](https://discuss.python.org/t/a-lightweight-cooperative-timeout-mechanism-for-synchronous-code-with-timeout-seconds/107811/19 "2026-06-23T16:06:56Z")

</div>

Since your post is actually exactly the same that was [proposed](https://discuss.python.org/t/add-an-opt-in-timeout-parameter-to-re-to-mitigate-catastrophic-backtracking/107766/4) in another thread some days ago, I repeat my concerns:

> [@Add an opt-in timeout parameter to re to mitigate catastrophic backtracking](https://discuss.python.org/t/add-an-opt-in-timeout-parameter-to-re-to-mitigate-catastrophic-backtracking/107766/10):
>
> The problem I see with such a generic solution is that it is quite brittle. The context manager `with timeout` could also be used to run any Python code. If the timeout fires, the cancellation […] could happen between any two bytecode instructions. So, if it was used in a generic way, it could leave any python object that is manipulated within the context manager in an invalid state (not keeping the invariants of the class). The Python docs explicitly warns about [this problem](https://docs.python.org/3/library/signal.html#note-on-signal-handlers-and-exceptions). […]

You emphasize that the mechanism would be “cooperative”. But the details of the proposal reveal that it is cooperative only at the C level (like signal handling; so C extensions can be hardened), but it is not cooperative at the Python level (so Python code cannot be not be hardened). So, the following would also be true if a timeout has fired:

> [@](#):
>
> Most Python code, including the standard library, cannot be made robust against this, and so a `KeyboardInterrupt` (or any other exception resulting from a signal handler) may on rare occasions put the program in an unexpected state. – [docs.python.org](https://docs.python.org/3/library/signal.html#note-on-signal-handlers-and-exceptions)

---

_[View the full topic](https://discuss.python.org/t/a-lightweight-cooperative-timeout-mechanism-for-synchronous-code-with-timeout-seconds/107811)._
