diff --git a/my/core/compat.py b/my/core/compat.py index 3c825f2..72970e3 100644 --- a/my/core/compat.py +++ b/my/core/compat.py @@ -125,3 +125,35 @@ else: else: from typing import Dict TypedDict = Dict + + +# bisect_left doesnt have a 'key' parameter (which we use) +# till python3.10 +if sys.version_info[:2] < (3, 9): + from typing import List, TypeVar, Any, Optional + X = TypeVar('X') + # copied from python src + def bisect_left(a: List[Any], x: Any, lo: int=0, hi: Optional[int]=None, *, key: Optional[Callable]=None) -> int: + if lo < 0: + raise ValueError('lo must be non-negative') + if hi is None: + hi = len(a) + # Note, the comparison uses "<" to match the + # __lt__() logic in list.sort() and in heapq. + if key is None: + while lo < hi: + mid = (lo + hi) // 2 + if a[mid] < x: + lo = mid + 1 + else: + hi = mid + else: + while lo < hi: + mid = (lo + hi) // 2 + if key(a[mid]) < x: + lo = mid + 1 + else: + hi = mid + return lo +else: + from bisect import bisect_left # type: ignore[misc] diff --git a/my/location/fallback/via_ip.py b/my/location/fallback/via_ip.py index e4c35a8..1da2315 100644 --- a/my/location/fallback/via_ip.py +++ b/my/location/fallback/via_ip.py @@ -23,11 +23,11 @@ class ip_config(location.via_ip): config = make_config(ip_config) -import bisect from functools import lru_cache from typing import Iterator, List from my.core.common import LazyLogger +from my.core.compat import bisect_left from my.ip.all import ips from my.location.common import Location from my.location.fallback.common import FallbackLocation, DateExact, _datetime_timestamp @@ -71,7 +71,7 @@ def estimate_location(dt: DateExact) -> Iterator[FallbackLocation]: # search to find the first possible location which contains dt (something that started up to # config.for_duration ago, and ends after dt) - idx = bisect.bisect_left(fl, dt_ts - config.for_duration.total_seconds(), key=lambda l: l.dt.timestamp()) # type: ignore[operator,call-arg,type-var] + idx = bisect_left(fl, dt_ts - config.for_duration.total_seconds(), key=lambda l: l.dt.timestamp()) # type: ignore[operator,call-arg,type-var] # all items are before the given dt if idx == len(fl):