How do I get the info for a cached property? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How do I get the info for a cached property? (/thread-12587.html) |
How do I get the info for a cached property? - arnavb - Sep-01-2018 Say I have the following class with a property that has an expensive operation: from functools import lru_cache class Example: @property @lru_cache(maxsize=None) def a_getter(self): print('Doing an expensive operation!') expensive_result = 5 return expensive_result test = Example() for i in range(0, 1000): a_variable = test.a_getter print(test.a_getter.cache_info())As evident, this does not run with 3.6.1, with the traceback: However, if I remove the property decorator, then the code works (I just have to switch to a function call for the getter).Is there a way for me to get this cache info with the property decorator as well? RE: How do I get the info for a cached property? - buran - Sep-02-2018 Maybe not the best, but from functools import lru_cache class Example: @property def a_getter(self): return self._a_getter() @lru_cache(maxsize=None) def _a_getter(self): print('Doing an expensive operation!') expensive_result = 5 return expensive_result test = Example() for i in range(0, 1000): a_variable = test.a_getter print(test._a_getter.cache_info())would be interesting to see other suggestions RE: How do I get the info for a cached property? - Gribouillis - Sep-02-2018 Use print(Example.a_getter.fget.cache_info()) RE: How do I get the info for a cached property? - arnavb - Sep-02-2018 Thanks guys! Both of your solutions worked, but @Gribouillis's solution fits my needs better. (Also unrelated question, but does this site have a method of marking threads solved or anything, by any chance?) |