1

I am using Python's DiskCache and the memoize decorator to cache function calls to a database of static data.


from diskcache import Cache
cache = Cache("database_cache)

@cache.memoize()
def fetch_document(row_id: int, user: str, password: str):
    ...

I don't want the user and password be part of the cache key.

How can I exclude parameters from the key generation?

Leevi L
  • 1,538
  • 2
  • 13
  • 28
  • 1
    base on documentation for [memoize](http://www.grantjenks.com/docs/diskcache/api.html#diskcache.FanoutCache.memoize) you can't exclude parameters. You will have to write own decorator. Or inside `fetch_document` use `cache[row_id] = result` with `if/else – furas May 07 '21 at 20:11

2 Answers2

2

Documentation for memoize doesn't show option to exclude parameters.

You may try to write own decorator - using source code.

Or use cache on your own inside fetch_document - something like this

def fetch_document(row_id: int, user: str, password: str):
    if row_id in cache:
         return cache[row_id]

    # ... code ...
              
    # result = ...

    cache[row_id] = result

    return result              

EDIT:

OR create cached version of your function - like this

def cached_fetch_document(row_id: int, user: str, password: str):
    if row_id in cache:
         return cache[row_id]

    result = fetch_document(row_id: int, user: str, password: str)

    cache[row_id] = result

    return result              

and later you can decide if you want to use cached_fetch_document in place of fetch_document

furas
  • 134,197
  • 12
  • 106
  • 148
  • 1
    I didn't know I could talk to the cache directly. I thought I have to use a decorator. This makes life much easier. I can treat `cache` like a dictionary that is stored in a file. It seems that parameters like `expire` that I usually pass to the decorator `@cache.memoize` can be set with `cach.set(expire)` – Leevi L May 08 '21 at 09:51
1

After version 5.3.0, memoize can use the ignore argument to ignore the positional arguments

MattonRoi
  • 109
  • 1
  • 5