A dictionary that prevents itself from growing too much.
| 367 | # A class useful for cache usage |
| 368 | # |
| 369 | class CacheDict(dict): |
| 370 | """A dictionary that prevents itself from growing too much.""" |
| 371 | |
| 372 | def __init__(self, maxentries: int) -> None: |
| 373 | self.maxentries = maxentries |
| 374 | super().__init__(self) |
| 375 | |
| 376 | def __setitem__(self, key: str, value: Any) -> None: |
| 377 | # Protection against growing the cache too much |
| 378 | if len(self) > self.maxentries: |
| 379 | # Remove a 10% of (arbitrary) elements from the cache |
| 380 | entries_to_remove = self.maxentries / 10 |
| 381 | for k in list(self)[:entries_to_remove]: |
| 382 | super().__delitem__(k) |
| 383 | super().__setitem__(key, value) |
| 384 | |
| 385 | |
| 386 | class NailedDict: |