Coverage for src/extratools_core/functools.py: 100%
31 statements
« prev ^ index » next coverage.py v7.8.1, created at 2025-06-19 04:20 -0700
« prev ^ index » next coverage.py v7.8.1, created at 2025-06-19 04:20 -0700
1from collections import Counter
2from collections.abc import Callable, Iterable
3from decimal import Decimal
4from statistics import mean
5from typing import Any, cast
8# Name it in this way to mimic as a function
9class lazy_call[T: Any]: # noqa: N801
10 __DEFAULT_OBJECT = object()
12 def __init__(
13 self,
14 func: Callable[..., T],
15 *args: Any,
16 **kwargs: Any,
17 ) -> None:
18 self.__func = func
19 self.__args = args
20 self.__kwargs = kwargs
22 self.__object: object | T = self.__DEFAULT_OBJECT
24 def __call__(self) -> T:
25 if self.__object == self.__DEFAULT_OBJECT:
26 self.__object = self.__func(*self.__args, **self.__kwargs)
28 return cast("T", self.__object)
31# Name it in this way to mimic as a function
32class multi_call[T: Any]: # noqa: N801
33 def __init__(
34 self,
35 times: int,
36 agg_func: Callable[[Iterable[T]], T],
37 ) -> None:
38 self.__times = times
39 self.__agg_func = agg_func
41 def __call__(
42 self,
43 func: Callable[..., T],
44 *args: Any,
45 **kwargs: Any,
46 ) -> T:
47 results = (
48 func(*args, **kwargs)
49 for i in range(self.__times)
50 )
52 return self.__agg_func(results)
55# Name it in this way to mimic as a function
56class multi_call_for_average[T: int | float | Decimal](multi_call[T]): # noqa: N801
57 def __init__(
58 self,
59 times: int,
60 ) -> None:
61 super().__init__(
62 times,
63 mean,
64 )
67# Name it in this way to mimic as a function
68class multi_call_for_most_common[T: Any](multi_call[T]): # noqa: N801
69 def __init__(
70 self,
71 times: int,
72 ) -> None:
73 def most_commmon(results: Iterable[T]) -> T:
74 return Counter(results).most_common(1)[0][0]
76 super().__init__(
77 times,
78 most_commmon,
79 )