3 from __future__ import annotations
5 import concurrent.futures as fut
8 from typing import Callable, List, TypeVar
10 from overrides import overrides
12 # This module is commonly used by others in here and should avoid
13 # taking any unnecessary dependencies back on them.
14 from deferred_operand import DeferredOperand
17 logger = logging.getLogger(__name__)
23 futures: List[SmartFuture],
25 callback: Callable = None,
26 log_exceptions: bool = True,
29 smart_future_by_real_future = {}
30 completed_futures = set()
32 assert type(f) == SmartFuture
33 real_futures.append(f.wrapped_future)
34 smart_future_by_real_future[f.wrapped_future] = f
36 while len(completed_futures) != len(real_futures):
37 newly_completed_futures = concurrent.futures.as_completed(real_futures)
38 for f in newly_completed_futures:
39 if callback is not None:
41 completed_futures.add(f)
42 if log_exceptions and not f.cancelled():
43 exception = f.exception()
44 if exception is not None:
46 f'Future {id(f)} raised an unhandled exception and exited.'
48 logger.exception(exception)
50 yield smart_future_by_real_future[f]
51 if callback is not None:
57 futures: List[SmartFuture],
59 log_exceptions: bool = True,
63 assert type(f) == SmartFuture
64 real_futures.append(f.wrapped_future)
66 (done, not_done) = concurrent.futures.wait(
67 real_futures, timeout=None, return_when=concurrent.futures.ALL_COMPLETED
70 for f in real_futures:
72 exception = f.exception()
73 if exception is not None:
75 f'Future {id(f)} raised an unhandled exception and exited.'
77 logger.exception(exception)
79 assert len(done) == len(real_futures)
80 assert len(not_done) == 0
83 class SmartFuture(DeferredOperand):
84 """This is a SmartFuture, a class that wraps a normal Future and can
85 then be used, mostly, like a normal (non-Future) identifier.
87 Using a FutureWrapper in expressions will block and wait until
88 the result of the deferred operation is known.
91 def __init__(self, wrapped_future: fut.Future) -> None:
92 assert type(wrapped_future) == fut.Future
93 self.wrapped_future = wrapped_future
94 self.id = id_generator.get("smart_future_id")
96 def get_id(self) -> int:
99 def is_ready(self) -> bool:
100 return self.wrapped_future.done()
102 # You shouldn't have to call this; instead, have a look at defining a
103 # method on DeferredOperand base class.
105 def _resolve(self, *, timeout=None) -> T:
106 return self.wrapped_future.result(timeout)