Python Forum

Full Version: How do I get the info for a cached property?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:

Error:
Traceback (most recent call last): File "python", line 16, in <module> AttributeError: 'int' object has no attribute 'cache_info'
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?
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
Use
print(Example.a_getter.fget.cache_info())
Thanks guys! Both of your solutions worked, but @Gribouillis's solution fits my needs better. Big Grin

(Also unrelated question, but does this site have a method of marking threads solved or anything, by any chance?)