Add an opt-in timeout parameter to re to mitigate catastrophic backtracking

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 (like triggered by a signal SIGALRM) 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. If it was restricted to the regex matching function, the semantics could be defined.

That would not work under Windows, see docs.

Correct, but this code exists and this is what allows you to abort your Python script also during Regex matches (like with Ctrl+C on Linux).

Not quite. Tim Peters asked for it to be discussed here first. This is what the OP did.

5 Likes