Skip to content
Advertisement

Can One Replace or Remove a specific key from functools.lru_cache?

I’m using a functools.lru_cache to serve temp file paths given certain input*. However in case the path no longer exists, I would like to remove/replace the single corresponding key. The cache_clear() method would be overkill and cache_info() do not appear to help.

Thanks for your help!

* The method being cached streams a fileobj from S3 to a local temp file.

Advertisement

Answer

This was requested via a python.org issue allow to cache_clear(some_key) in lru_cache and rejected. So there is no method in lru_cache that clears a specific entry.

There is an excellent suggestion linked from that issue to implement your own variant using collections.OrderedDict called Foundation for rolling your own LRU cache variants.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement