lru

How to combine dataclass, property, and lru_cache

How to combine dataclass, property, and lru_cache Question: I’m trying to combine dataclasses, properties and lru_caches for some computational science code: from dataclasses import dataclass from typing import Any from functools import lru_cache @dataclass class F: a: Any = 1 b: Any = 2 c: Any = 3 @property @lru_cache(1) def d(self): print(‘Computing d’) return …

Total answers: 1

How does Lru_cache (from functools) Work?

How does Lru_cache (from functools) Work? Question: Especially when using recursive code there are massive improvements with lru_cache. I do understand that a cache is a space that stores data that has to be served fast and saves the computer from recomputing. How does the Python lru_cache from functools work internally? I’m Looking for a …

Total answers: 3

Python functools lru_cache with instance methods: release object

Python functools lru_cache with instance methods: release object Question: How can I use functools.lru_cache inside classes without leaking memory? In the following minimal example the foo instance won’t be released although going out of scope and having no referrer (other than the lru_cache). from functools import lru_cache class BigClass: pass class Foo: def __init__(self): self.big …

Total answers: 9

Make @lru_cache ignore some of the function arguments

Make @lru_cache ignore some of the function arguments Question: How can I make @functools.lru_cache decorator ignore some of the function arguments with regard to caching key? For example, I have a function that looks like this: def find_object(db_handle, query): # (omitted code) return result If I apply lru_cache decorator just like that, db_handle will be …

Total answers: 2

Python LRU Cache Decorator Per Instance

Python LRU Cache Decorator Per Instance Question: Using the LRU Cache decorator found here: http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/ from lru_cache import lru_cache class Test: @lru_cache(maxsize=16) def cached_method(self, x): return x + 5 I can create a decorated class method with this but it ends up creating a global cache that applies to all instances of class Test. However, …

Total answers: 3

How to limit the size of a dictionary?

How to limit the size of a dictionary? Question: I’d like to work with a dict in python, but limit the number of key/value pairs to X. In other words, if the dict is currently storing X key/value pairs and I perform an insertion, I would like one of the existing pairs to be dropped. …

Total answers: 7