Used isort to sort imports. Also added to the git pre-commit hook.
[python_utils.git] / parallelize.py
1 #!/usr/bin/env python3
2
3 """A decorator to help with dead simple parallelization."""
4
5
6 import atexit
7 import functools
8 import typing
9 from enum import Enum
10
11
12 class Method(Enum):
13     THREAD = 1
14     PROCESS = 2
15     REMOTE = 3
16
17
18 def parallelize(
19     _funct: typing.Optional[typing.Callable] = None, *, method: Method = Method.THREAD
20 ) -> typing.Callable:
21     """Usage:
22
23         @parallelize    # defaults to thread-mode
24         def my_function(a, b, c) -> int:
25             ...do some slow / expensive work, e.g., an http request
26
27         @parallelize(method=Method.PROCESS)
28         def my_other_function(d, e, f) -> str:
29             ...do more really expensice work, e.g., a network read
30
31         @parallelize(method=Method.REMOTE)
32         def my_other_other_function(g, h) -> int:
33             ...this work will be distributed to a remote machine pool
34
35     This decorator will invoke the wrapped function on:
36
37         Method.THREAD (default): a background thread
38         Method.PROCESS: a background process
39         Method.REMOTE: a process on a remote host
40
41     The wrapped function returns immediately with a value that is
42     wrapped in a SmartFuture.  This value will block if it is either
43     read directly (via a call to result._resolve) or indirectly (by
44     using the result in an expression, printing it, hashing it,
45     passing it a function argument, etc...).  See comments on the
46     SmartFuture class for details.
47
48     Note: you may stack @parallelized methods and it will "work".
49     That said, having multiple layers of Method.PROCESS or
50     Method.REMOTE may prove to be problematic because each process in
51     the stack will use its own independent pool which may overload
52     your machine with processes or your network with remote processes
53     beyond the control mechanisms built into one instance of the pool.
54     Be careful.
55
56     Also note: there is a non trivial overhead of pickling code and
57     scp'ing it over the network when you use Method.REMOTE.  There's
58     a smaller but still considerable cost of creating a new process
59     and passing code to/from it when you use Method.PROCESS.
60     """
61
62     def wrapper(funct: typing.Callable):
63         @functools.wraps(funct)
64         def inner_wrapper(*args, **kwargs):
65             import executors
66             import smart_future
67
68             # Look for as of yet unresolved arguments in _funct's
69             # argument list and resolve them now.
70             newargs = []
71             for arg in args:
72                 newargs.append(smart_future.SmartFuture.resolve(arg))
73             newkwargs = {}
74             for kw in kwargs:
75                 newkwargs[kw] = smart_future.SmartFuture.resolve(kwargs[kw])
76
77             executor = None
78             if method == Method.PROCESS:
79                 executor = executors.DefaultExecutors().process_pool()
80             elif method == Method.THREAD:
81                 executor = executors.DefaultExecutors().thread_pool()
82             elif method == Method.REMOTE:
83                 executor = executors.DefaultExecutors().remote_pool()
84             assert executor is not None
85             atexit.register(executors.DefaultExecutors().shutdown)
86
87             future = executor.submit(funct, *newargs, **newkwargs)
88
89             # Wrap the future that's returned in a SmartFuture object
90             # so that callers do not need to call .result(), they can
91             # just use is as normal.
92             return smart_future.SmartFuture(future)
93
94         return inner_wrapper
95
96     if _funct is None:
97         return wrapper
98     else:
99         return wrapper(_funct)