summaryrefslogtreecommitdiff
path: root/dots_manager/utils.py
blob: 1b900f01f6abb4f6f2d9803d8acbb4f9f5f86573 (plain)
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
import logging
from typing import Callable, Optional, TypeVar, Tuple, ParamSpec, Dict, Any, List
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import reduce

P = ParamSpec("P")
T = TypeVar("T")
R = TypeVar("R")


def is_some(
    callable: Callable[P, Optional[T]], *args: P.args, **kwargs: P.kwargs
) -> Tuple[bool, Optional[T]]:
    result = callable(*args, **kwargs)
    return result is not None, result


def merge_dicts(*dicts: Dict[str, Any]) -> Dict[str, Any]:
    def merge(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
        out = dict(a)
        for k, v in b.items():
            if k in out and isinstance(out[k], dict) and isinstance(v, dict):
                out[k] = merge(out[k], v)
            else:
                out[k] = v
        return out

    return reduce(merge, dicts, {})


def parallelize(
    worker: Callable[[T], R],
    items: List[T],
    logger: logging.Logger,
    executor: Optional[ThreadPoolExecutor] = None,
) -> List[R]:
    if executor is None:
        from dots_manager.config import Constants

        executor = ThreadPoolExecutor(max_workers=Constants.max_workers)
    with executor as exec:
        futures = [exec.submit(worker, item) for item in items]
        logger.info(f"submitted {len(futures)} tasks to executor <_mood.excited>")
        return [f.result() for f in as_completed(futures)]