mirror of
https://github.com/jdejaegh/python-irceline.git
synced 2025-06-27 03:35:56 +02:00
Create SizedDict
This commit is contained in:
parent
800f87cf38
commit
8bbddacfe9
2 changed files with 52 additions and 0 deletions
22
src/open_irceline/utils.py
Normal file
22
src/open_irceline/utils.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
from collections import OrderedDict
|
||||
|
||||
|
||||
class SizedDict(OrderedDict):
|
||||
"""Dictionary with a maximum size. When more items are added, the least recently accessed element is evicted"""
|
||||
|
||||
def __init__(self, size: int):
|
||||
super().__init__()
|
||||
self._size = size
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
super().__setitem__(key, value)
|
||||
self.move_to_end(key)
|
||||
if len(self) > self._size:
|
||||
self.popitem(False)
|
||||
|
||||
def __getitem__(self, key):
|
||||
super().__getitem__(key)
|
||||
self.move_to_end(key)
|
||||
|
||||
def update(self, __m, **kwargs):
|
||||
raise NotImplementedError()
|
30
tests/test_sized_dict.py
Normal file
30
tests/test_sized_dict.py
Normal file
|
@ -0,0 +1,30 @@
|
|||
from src.open_irceline.utils import SizedDict
|
||||
|
||||
|
||||
def test_size_dict():
|
||||
s_dict = SizedDict(5)
|
||||
assert len(s_dict) == 0
|
||||
|
||||
s_dict['a'] = 1
|
||||
s_dict['b'] = 2
|
||||
s_dict['c'] = 3
|
||||
s_dict['d'] = 4
|
||||
s_dict['e'] = 5
|
||||
assert len(s_dict) == 5
|
||||
|
||||
s_dict['f'] = 6
|
||||
assert 'a' not in s_dict
|
||||
assert 'f' in s_dict
|
||||
assert len(s_dict) == 5
|
||||
|
||||
s_dict['b'] = 42
|
||||
s_dict['g'] = 7
|
||||
assert 'f' in s_dict
|
||||
assert 'g' in s_dict
|
||||
assert 'b' in s_dict
|
||||
assert 'c' not in s_dict
|
||||
assert len(s_dict) == 5
|
||||
|
||||
del s_dict['b']
|
||||
assert len(s_dict) == 4
|
||||
assert 'b' not in s_dict
|
Loading…
Add table
Reference in a new issue