Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`DummyExecutor` for Python's `futures`

Python's futures package allows us to enjoy ThreadPoolExecutor and ProcessPoolExecutor for doing tasks in parallel.

However, for debugging it is sometimes useful to temporarily replace the true parallelism with a dummy one, which carries out the tasks in a serial way in the main thread, without spawning any threads or processes.

Is there anywhere an implementation of a DummyExecutor?

like image 854
Ram Rachum Avatar asked May 03 '12 15:05

Ram Rachum


People also ask

What is the purpose of processpoolexecutor in Python?

From Python 3.2 onwards a new class called ProcessPoolExecutor was introduced in python in concurrent. The futures module to efficiently manage and create Process. But wait, if python already had a multiprocessing module inbuilt then why a new module was introduced. Let me answer this first.

Can I use concurrent futures on Python 3?

This is a backport of the concurrent.futures standard library module to Python 2. It does not work on Python 3 due to Python 2 syntax being used in the codebase. Python 3 users should not attempt to install it, since the package is already included in the standard library.

What is futurize in Python?

An included script called futurize aids in converting code (from either Python 2 or Python 3) to code compatible with both platforms. It is similar to python-modernize but goes further in providing Python 3 compatibility through the use of the backported types and builtin functions in future.

What is the Max_workers of a processpoolexecutor?

concurrent.futures.ProcessPoolExecutor (max_workers=None, mp_context=”, initializer=None, initargs= ()) max_workers: It is number of Process aka size of pool.


1 Answers

Something like this should do it:

from concurrent.futures import Future, Executor
from threading import Lock


class DummyExecutor(Executor):

    def __init__(self):
        self._shutdown = False
        self._shutdownLock = Lock()

    def submit(self, fn, *args, **kwargs):
        with self._shutdownLock:
            if self._shutdown:
                raise RuntimeError('cannot schedule new futures after shutdown')

            f = Future()
            try:
                result = fn(*args, **kwargs)
            except BaseException as e:
                f.set_exception(e)
            else:
                f.set_result(result)

            return f

    def shutdown(self, wait=True):
        with self._shutdownLock:
            self._shutdown = True


if __name__ == '__main__':

    def fnc(err):
        if err:
            raise Exception("test")
        else:
            return "ok"

    ex = DummyExecutor()
    print(ex.submit(fnc, True))
    print(ex.submit(fnc, False))
    ex.shutdown()
    ex.submit(fnc, True) # raises exception

locking is probably not needed in this case, but can't hurt to have it.

like image 169
mata Avatar answered Oct 14 '22 19:10

mata