Skip to content

Commit ff9404c

Browse files
committed
Add cache class
1 parent 7ad59f0 commit ff9404c

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

sonar/util/cache.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,33 +21,50 @@
2121
"""Cache manager"""
2222

2323
from typing import Optional
24+
from sonar import logging as log
2425

2526

2627
class Cache(object):
2728
"""Abstract cache implementation"""
2829

2930
def __init__(self) -> None:
31+
"""Constructor"""
3032
self.objects = {}
33+
self.object_class = None
3134

3235
def __len__(self) -> int:
3336
"""Returns size of cache"""
3437
return len(self.objects)
3538

3639
def __str__(self) -> str:
40+
"""string repr of Cache"""
41+
return "'undefined class' cache" if not self.object_class else f"'{self.object_class.__name__}' cache"
42+
43+
def set_class(self, object_class: object) -> None:
44+
self.object_class = object_class
45+
46+
def contents(self) -> str:
47+
"""Returns the cache contents as a string"""
3748
return ", ".join([str(o) for o in self.objects.values()])
3849

3950
def put(self, obj: object) -> object:
4051
"""Add an object in cache if not already present"""
4152
h = hash(obj)
4253
if h not in self.objects:
4354
self.objects[h] = obj
55+
else:
56+
log.debug("%s already in cache, can't be added again", obj)
57+
# log.debug("PUT %s: %s", self, self.contents())
4458
return self.objects[h]
4559

4660
def get(self, *args) -> Optional[object]:
61+
# log.debug("GET %s: %s", self, self.contents())
4762
return self.objects.get(hash(args), None)
4863

4964
def pop(self, obj: object) -> Optional[object]:
50-
return self.objects.pop(hash(obj), None)
65+
o = self.objects.pop(hash(obj), None)
66+
log.debug("POP %s: %s", self, self.contents())
67+
return o
5168

5269
def values(self) -> list[object]:
5370
return list(self.objects.values())
@@ -59,4 +76,6 @@ def items(self) -> dict[int, object]:
5976
return self.objects.items()
6077

6178
def clear(self) -> None:
79+
"""Clears a cache"""
80+
# log.info("Clearing %s", self)
6281
self.objects = {}

0 commit comments

Comments
 (0)