A set with a maximum size that evicts the oldest items when necessary. This class does not implement the complete set interface.
| 12 | |
| 13 | |
| 14 | class BoundedSet: |
| 15 | """A set with a maximum size that evicts the oldest items when necessary. |
| 16 | |
| 17 | This class does not implement the complete set interface. |
| 18 | |
| 19 | """ |
| 20 | |
| 21 | def __contains__(self, item: Any) -> bool: |
| 22 | """Test if the :class:`.BoundedSet` contains item.""" |
| 23 | self._access(item) |
| 24 | return item in self._set |
| 25 | |
| 26 | def __init__(self, max_items: int) -> None: |
| 27 | """Initialize a :class:`.BoundedSet` instance.""" |
| 28 | self.max_items = max_items |
| 29 | self._set = OrderedDict() |
| 30 | |
| 31 | def _access(self, item: Any) -> None: |
| 32 | if item in self._set: |
| 33 | self._set.move_to_end(item) |
| 34 | |
| 35 | def add(self, item: Any) -> None: |
| 36 | """Add an item to the set discarding the oldest item if necessary.""" |
| 37 | self._access(item) |
| 38 | self._set[item] = None |
| 39 | if len(self._set) > self.max_items: |
| 40 | self._set.popitem(last=False) |
| 41 | |
| 42 | |
| 43 | class ExponentialCounter: |
no outgoing calls
searching dependent graphs…