2121"""Cache manager"""
2222
2323from typing import Optional
24+ from sonar import logging as log
2425
2526
2627class 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