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