Per-Job Exceptions

Step 3: Per-Job Exceptions

One bad job shouldn't take down the whole batch. If a job raises, capture the exception on its future and keep going, other jobs still run, and the error surfaces only when someone calls that future's result().

Update run(): wrap each job call in try/except and route a raised exception to fut.set_exception(...) instead of letting it escape.

Hints
Starter code
from collections import deque


class Future:
    def __init__(self):
        self._done = False
        self._result = None
        self._exc = None

    def set_result(self, value):
        self._result = value
        self._done = True

    def set_exception(self, exc):
        self._exc = exc
        self._done = True

    def done(self):
        return self._done

    def result(self):
        if not self._done:
            raise RuntimeError("future is not done")
        if self._exc is not None:
            raise self._exc
        return self._result


class ThreadPool:
    def __init__(self, num_workers):
        self.num_workers = num_workers
        self._queue = deque()

    def submit(self, fn, *args, **kwargs):
        fut = Future()
        self._queue.append((fut, fn, args, kwargs))
        return fut

    def run(self):
        """Run all jobs; a job that raises fails only its own future."""
        while self._queue:
            fut, fn, args, kwargs = self._queue.popleft()
            # TODO: wrap the call in try/except:
            #   try: fut.set_result(fn(*args, **kwargs))
            #   except Exception as e: fut.set_exception(e)
            pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.