19/41
Part 4 of 7 · VersionsLearn

Each key keeps its times and values in two lists, searched with bisect_right

Each key gets its changes in time order, as two lists: the times, and the values at the same positions. With the times in a list of their own, bisect searches plain numbers. It needs no key function, and no tuples that compare values on a tie.

from bisect import bisect_right

# a marker that can't be equal to any real value
DELETED = object()


class Versions:
    def __init__(self):
        # key -> its change times, sorted
        self.times = {}
        # key -> the value at the same position
        self.values = {}

    def set(self, key, value, time):
        times = self.times.setdefault(key, [])
        values = self.values.setdefault(key, [])
        # after any change at the same time
        i = bisect_right(times, time)
        times.insert(i, time)
        values.insert(i, value)

    def delete(self, key, time):
        self.set(key, DELETED, time)

    def get(self, key, time):
        times = self.times.get(key, [])
        # how many changes are at or before time
        i = bisect_right(times, time)
        if i == 0:
            return None
        value = self.values[key][i - 1]
        return None if value is DELETED else value


store = Versions()
store.set("timeout", 30, 100)
store.set("timeout", 45, 160)
store.set("timeout", 60, 220)
print([store.get("timeout", t) for t in (99, 100, 159.5, 160, 219, 220, 10**9)])
[None, 30, 30, 45, 45, 60, 60]

bisect_right answers an edge in each place it's used:

  • A read exactly at a change sees it. bisect_right(times, time) counts the changes at or before time, so a read at 160 counts the change at 160. With bisect_left, a read at 160 would still see 30.
  • Two changes at the same time go to the later call. bisect_right inserts the new change after the old one, and a read takes the last change it counts.

Here is a tie:

store.set("mode", "z-old", 100)
store.set("mode", "a-new", 100)
print(store.times["mode"], store.values["mode"], store.get("mode", 100))
[100, 100] ['z-old', 'a-new'] a-new