Home Assistant Unofficial Reference 2024.12.1
variance.py
Go to the documentation of this file.
1 """Util functions to help filter out similar results."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from datetime import datetime, timedelta
7 import functools
8 from typing import Any, overload
9 
10 
11 @overload
12 def ignore_variance[**_P](
13  func: Callable[_P, int], ignored_variance: int
14 ) -> Callable[_P, int]: ...
15 
16 
17 @overload
18 def ignore_variance[**_P](
19  func: Callable[_P, float], ignored_variance: float
20 ) -> Callable[_P, float]: ...
21 
22 
23 @overload
24 def ignore_variance[**_P](
25  func: Callable[_P, datetime], ignored_variance: timedelta
26 ) -> Callable[_P, datetime]: ...
27 
28 
29 def ignore_variance[**_P, _R: (int, float, datetime)](
30  func: Callable[_P, _R], ignored_variance: Any
31 ) -> Callable[_P, _R]:
32  """Wrap a function that returns old result if new result does not vary enough."""
33  last_value: _R | None = None
34 
35  @functools.wraps(func)
36  def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
37  nonlocal last_value
38 
39  value = func(*args, **kwargs)
40 
41  if last_value is not None and abs(value - last_value) < ignored_variance:
42  return last_value
43 
44  last_value = value
45  return value
46 
47  return wrapper