8000 Invalidating cached values in "cachemethod" · Issue #218 · tkem/cachetools · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Invalidating cached values in "cachemethod" #218
Open
@ShivKJ

Description

@ShivKJ

Hi,

Is there a way to update/remove cache value returned by cachemethod?

For example, in the below code,

import operator as op
from dataclasses import dataclass, field

from cachetools import TTLCache, cachedmethod


@dataclass
class A:
    cache: TTLCache = field(init=False)

    def __post_init__(self):
        self.cache = TTLCache(maxsize=32, ttl=2 * 3600)

    @cachedmethod(cache=op.attrgetter('cache'))
    def compute(self, i):
        print('value of i', i)
        return i * 2

Suppose, I want to remove cached value for a given i from cache, then it is not possible to do directly.

Meanwhile, I learned about hashkey function in keys module. But it is not exposed in cachetools __init__, so can not be imported (of course there are hacks around it). Using this, we can updated cached value.


So, I think there could be two solutions to it,

  1. As cachemethod wraps a method to enable caching feature in it, so apart from the caching feature, it can add functionality to invalidate. For example,
a = A()

print(a.compute(10))

a.compute.remove(10) # remove can have signature *args, **kwargs. Instead of word `remove`, a more better function name can be thought
  1. Exposing keys module in cachetools __init__.py.
from cachetools.keys import hashkey

a = A()

i = 10
print(a.compute(i))

del a.cache[hashkey(i)]

I think approach 1 would be more user friendly.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0