markov: More refined usage of Chain.__touch()

This moves the self.__touch() call around in markov's Chain class such
that it will only access truly available data.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
This commit is contained in:
2022-06-03 18:21:34 -07:00
parent da7d1501e2
commit 04c0d05208

View File

@@ -52,10 +52,10 @@ class Chain:
return self.__last_access
def add(self, text: str):
self.__touch()
parts: List[Any] = text.strip().split()
if not parts:
return
self.__touch()
self.__load()
for fragment in windows(parts + [None], self.order + 1):
head = fragment[0:-1]
@@ -64,15 +64,16 @@ class Chain:
self.__dirty = True
def get(self, key: str) -> dict[str | None, int]:
self.__touch()
if self.__cache:
if key in self.__cache:
self.__touch()
return self.__cache[key]
else:
raise KeyError(key)
else:
# Load cache, then return key
self.__load()
self.__touch()
return self.__cache[key]
def set(self, key: str, value: Mapping[str | None, int]):