Skip to content
Open
Show file tree
Hide file tree
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
47 changes: 32 additions & 15 deletions deepdiff/lfucache.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,50 @@
from collections import defaultdict
from cachebox import LRUCache
from collections import OrderedDict, defaultdict
from threading import Lock
from deepdiff.helper import SetOrdered, not_found


class DistanceCache:
"""
Native bounded cache used by DeepDiff's distance calculations.
Bounded LRU cache used by DeepDiff's distance calculations.

DeepDiff historically used a pure Python LFU cache here. The distance-cache
hot path benefits more from cachebox's native mapping operations than from
preserving LFU eviction semantics.
Built on ``collections.OrderedDict`` so DeepDiff has no compiled
dependency for caching. A lock keeps the compound get/move and
set/evict operations safe when a cache is shared across threads,
including on free-threaded Python builds.
"""

__slots__ = ('cache', 'capacity', 'lock')

def __init__(self, capacity):
if capacity <= 0:
raise ValueError('Capacity of DistanceCache needs to be positive.') # pragma: no cover.
self.cache = LRUCache(capacity)
self.cache = OrderedDict()
self.capacity = capacity
self.lock = Lock()

def get(self, key):
return self.cache.get(key, not_found)
with self.lock:
cache = self.cache
try:
value = cache[key]
except KeyError:
return not_found
cache.move_to_end(key)
return value

def set(self, key, report_type=None, value=None):
if report_type:
content = self.cache.get(key, None)
if content is None:
content = defaultdict(SetOrdered)
content[report_type].add(value)
value = content
self.cache.insert(key, value)
with self.lock:
cache = self.cache
if report_type:
content = cache.get(key)
if content is None:
content = defaultdict(SetOrdered)
content[report_type].add(value)
value = content
cache[key] = value
cache.move_to_end(key)
if len(cache) > self.capacity:
cache.popitem(last=False)

def __contains__(self, key):
return key in self.cache
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ build-backend = "flit_core.buildapi"
name = "deepdiff"
version = "9.2.1"
dependencies = [
"cachebox>=6.1.2,<7",
"orderly-set>=5.5.0,<6",
]
requires-python = ">=3.11"
Expand Down
Loading
Loading