Strange behavior with prints inside lru_cached properties
hroskes opened this issue · comments
class A:
def __init__(self):
self.b = 3
@methodtools.lru_cache()
@property
def a(self):
print("here")
print("here", self.b)
return self.b
When I run this code, I get the printout here
. The print statement seems to run at the time of class creation.
If I then do
a = A()
a.a
I get
here
here 3
as expected.
This is weird, but I am not sure methodtools can avoid that behavior. It seems like a side effect from decorator detection.
I want to recommend cached_property
for this use case.
Official: https://docs.python.org/dev/library/functools.html?highlight=s#functools.cached_property
For python < 3.8: https://pypi.org/search/?q=cached+property
I decided to add special handling for built-in property, thank you!