Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

python - How to exclude parameters when caching function calls with DiskCache and memoize?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...