-
Notifications
You must be signed in to change notification settings - Fork 451
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
33 changed files
with
1,026 additions
and
638 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
from collections import OrderedDict | ||
|
||
|
||
class LimitedOrderedDict(OrderedDict): | ||
""" This class is an implementation of OrderedDict with size limit. | ||
If the size of the dict exceeds the limit, the oldest entries will be deleted. | ||
""" | ||
def __init__(self, *args, limit: int = 200, **kwargs): | ||
self.limit = limit | ||
super().__init__(*args, **kwargs) | ||
|
||
def __setitem__(self, key, value): | ||
super().__setitem__(key, value) | ||
self._adjust_size() | ||
|
||
def _adjust_size(self): | ||
while len(self) > self.limit: | ||
self.popitem(last=False) |
27 changes: 27 additions & 0 deletions
27
src/tribler/core/utilities/tests/test_limited_ordered_dict.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
from tribler.core.utilities.limited_ordered_dict import LimitedOrderedDict | ||
|
||
|
||
def test_order(): | ||
d = LimitedOrderedDict() | ||
d['first'] = '1' | ||
d['second'] = '2' | ||
d['third'] = '3' | ||
|
||
assert list(d.keys()) == ['first', 'second', 'third'] | ||
|
||
|
||
def test_limit(): | ||
d = LimitedOrderedDict(limit=2) | ||
d['first'] = '1' | ||
d['second'] = '2' | ||
d['third'] = '3' | ||
|
||
assert list(d.keys()) == ['second', 'third'] | ||
|
||
|
||
def test_merge(): | ||
d1 = {'first': 1, 'second': 2} | ||
d2 = {'third': 3, 'fourth': 4} | ||
|
||
d = LimitedOrderedDict({**d1, **d2}, limit=2) | ||
assert len(d) == 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.