Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 11 additions & 2 deletions src/gt4py/eve/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,15 @@ def inner(*args: Any, **kwargs: Any) -> Any:
return _decorator(func) if func is not None else _decorator


class _LRUCacheValue(HashableBy):
__hash__ = HashableBy.__hash__

# we compare by hash here as the cache lookup in lru_cache is not only by hash but also by
# equality, but we only want to consider the key given by the user not the value.
def __eq__(self, other: Any) -> bool:
return hash(self) == hash(other)


# TODO(egparedes): it would be more efficient to implement the caching logic
# here instead of relying on `functools.lru_cache` and wrapping/unwrapping the
# arguments.
Expand Down Expand Up @@ -504,8 +513,8 @@ def cached_func(*args: HashableBy, **kwargs: HashableBy) -> _T:
@functools.wraps(func)
def inner(*args, **kwargs): # type: ignore[no-untyped-def] # cast below restores type info
return cached_func(
*(hashable_by(key, arg) for arg in args),
**{k: hashable_by(key, arg) for k, arg in kwargs.items()},
*(_LRUCacheValue(key, arg) for arg in args),
**{k: _LRUCacheValue(key, arg) for k, arg in kwargs.items()},
)

inner.cache_parameters = cached_func.cache_parameters # type: ignore[attr-defined] # mypy not aware of functools.lru_cache behavior
Expand Down
16 changes: 16 additions & 0 deletions tests/eve_tests/unit_tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,22 @@ def func(x):
assert cached.cache_info().misses == 1


def test_lru_cache_no_eq_call():
class A:
def __hash__(self) -> int:
return 1

def __eq__(self, other):
raise ValueError() # this function should never be called

@eve.utils.lru_cache(key=lambda x: hash(x))
def func(x):
pass

func(A())
func(A())


def test_fluid_partial():
from gt4py.eve.utils import fluid_partial

Expand Down
Loading