Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to add trigger on delete #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 21 additions & 10 deletions expiringdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import time
from threading import RLock
import sys
from typing import Any, Union
from typing import Any, Union, Optional, Callable

try:
from collections import OrderedDict
Expand All @@ -28,8 +28,11 @@


class ExpiringDict(OrderedDict):
def __init__(self, max_len, max_age_seconds, items=None):
# type: (Union[int, None], Union[float, None], Union[None,dict,OrderedDict,ExpiringDict]) -> None
def __init__(self,
max_len: int,
max_age_seconds: float,
items: Optional[Union[dict, OrderedDict, 'ExpiringDict']] = None,
on_delete: Optional[Callable] = None) -> None:

if not self.__is_instance_of_expiring_dict(items):
self.__assertions(max_len, max_age_seconds)
Expand All @@ -39,6 +42,8 @@ def __init__(self, max_len, max_age_seconds, items=None):
self.max_age = max_age_seconds
self.lock = RLock()

self.on_delete = on_delete

if sys.version_info >= (3, 5):
self._safe_keys = lambda: list(self.keys())
else:
Expand Down Expand Up @@ -88,18 +93,24 @@ def __getitem__(self, key, with_age=False):
def __setitem__(self, key, value, set_time=None):
""" Set d[key] to value. """
with self.lock:
if key in self:
OrderedDict.__delitem__(self, key)

if len(self) == self.max_len:
if key in self:
del self[key]
else:
try:
self.popitem(last=False)
except KeyError:
pass
try:
self.popitem(last=False)
except KeyError:
pass
if set_time is None:
set_time = time.time()
OrderedDict.__setitem__(self, key, (value, set_time))

def __delitem__(self, key):
if callable(self.on_delete):
value, _ = OrderedDict.__getitem__(self, key)
self.on_delete(key, value)
OrderedDict.__delitem__(self, key)

def pop(self, key, default=None):
""" Get item from the dict and remove it.

Expand Down