Calling a Python function with a timeout

In Python 3.13+ with pyrepl, my rpn calculator can show the result of evaluating some code while the user is entering it at the prompt.

Most code is trivial (e.g., 3 4 5 * * to multiply some numbers together) but complex code including recursion is possible. This can give code that runs for quite a long time! It's one thing if this happens when you hit enter, but another when there's the possibility that the repl freezes in the middle of entering some code.

There are various recipes for running Python code with timeout, but I wrote my own. Then, just for extra fun, I made it properly type check with ty.

I didn't integrate it into pydc yet but that part shouldn't be hard.

See the docstring of the function for some additional caveats.

View oj9ix6p1/timeout.py on codeberg.org or download raw


Entry first conceived on 20 July 2026, 14:52 UTC, last modified on 20 July 2026, 16:49 UTC
Website Copyright © 2004-2024 Jeff Epler