-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathselect.py
More file actions
67 lines (54 loc) · 2.2 KB
/
select.py
File metadata and controls
67 lines (54 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from concurrent.futures import Future
from typing import Any, Optional
class FutureSelector(Future):
def __init__(self, future: Future, selector: int | str):
self._future = future
self._selector = selector
super().__init__()
def __getattr__(self, attr: str) -> Any:
return getattr(self._future, attr)
def __setattr__(self, name: str, value: Any):
if name in ["_future", "_selector"]:
super().__setattr__(name, value)
else:
setattr(self._future, name, value)
def result(self, timeout: Optional[float] = None) -> Any:
result = self._future.result(timeout=timeout)
if result is not None:
if (
isinstance(self._selector, int) and isinstance(result, (tuple, list))
) or self._selector in result:
return result[self._selector]
else:
raise KeyError(
str(self._selector)
+ " of type "
+ str(type(self._selector))
+ " is not in "
+ str(result)
+ " of type "
+ str(type(result))
)
else:
return None
def split_future(future: Future, n: int) -> list[FutureSelector]:
"""
Split a concurrent.futures.Future object which returns a tuple or list as result into individual future objects
Args:
future (Future): future object which returns a tuple or list as result
n: number of elements expected in the future object
Returns:
list: List of future objects
"""
return [FutureSelector(future=future, selector=i) for i in range(n)]
def get_item_from_future(future: Future, key: str) -> FutureSelector:
"""
Get item from concurrent.futures.Future object which returns a dictionary as result by the corresponding dictionary
key.
Args:
future (Future): future object which returns a dictionary as result
key (str): dictionary key to get item from dictionary
Returns:
FutureSelector: Future object which returns the value corresponding to the key
"""
return FutureSelector(future=future, selector=key)