vendorize bisect_left from python src

doesnt have a 'key' parameter till python3.10
This commit is contained in:
Sean Breckenridge 2023-02-27 00:32:15 -08:00
parent e8b0973221
commit 2e780ac455
2 changed files with 34 additions and 2 deletions

View file

@ -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]

View file

@ -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):