Futures

Step 1: Futures

A pool runs work you hand it later, so submit can't return a value directly. It returns a future, a placeholder that will hold the result (or an error) once the job runs.

Implement Future:

  • set_result(value): store a successful result and mark done
  • set_exception(exc): store an error and mark done
  • done(): whether the future has been fulfilled
  • result(): return the value; if the job raised, re-raise that exception; if it isn't done yet, raise RuntimeError
Hints
Starter code
class Future:
    def __init__(self):
        self._done = False
        self._result = None
        self._exc = None

    def set_result(self, value):
        # TODO: store value and mark done
        pass

    def set_exception(self, exc):
        # TODO: store exc and mark done
        pass

    def done(self):
        # TODO
        pass

    def result(self):
        """Return the value, re-raise a stored exception, or raise RuntimeError if not done."""
        # TODO:
        #   if not self._done: raise RuntimeError("future is not done")
        #   if self._exc is not None: raise self._exc
        #   return self._result
        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.