I would like to know what is the python way of initializing a class member but only when accessing it, if accessed. I tried the code below and it is working but is there somethi
This answer is for a typical instance attribute/method only, not for a class attribute/classmethod
, or staticmethod
.
For Python 3.8+, how about using the cached_property decorator? It memoizes.
from functools import cached_property
class MyClass:
@cached_property
def my_lazy_attr(self):
print("Initializing and caching attribute, once per class instance.")
return 7**7**8
For Python 3.2+, how about using both property and lru_cache decorators? The latter memoizes.
from functools import lru_cache
class MyClass:
@property
@lru_cache()
def my_lazy_attr(self):
print("Initializing and caching attribute, once per class instance.")
return 7**7**8
Credit: answer by Maxime R.