Suppose I have some expensive function expensive_computation which takes a long time to compute but it always returns the same value.
I want to avoid paying the cost of computing this function because it may never be called.
Here is my solution to this, is there a more obvious or clean way to do it? Or maybe even some function from the standard library?
def lazy(function):
internal_state = None
def lazy_evaluation():
nonlocal internal_state
if internal_state is None:
internal_state = function()
return internal_state
return lazy_evaluation
@lazy
def expensive_computation():
print("Working ...")
return "that was hard"
print(expensive_computation())
print(expensive_computation())
Which prints:
Working ...
that was hard
that was hard
lazyup for review, and do you want any and all facets of your code reviewed? Please ensure your question is otherwise on-topic. \$\endgroup\$lazyor the use of such a construct is what I'm looking for. I'm not sure what you mean by "real code", it's some working code, where I replaced every piece on which I don't want advice on by dummy code (I don't need advice on the content ofexpensive_computation, that's why I don't provide its implementation). On the other hand, the implementation oflazyis the exact one I intend to use. I added the output to make clear what behaviour I expect (because I noticed the term "lazy evaluation" is actually broader than this use case). \$\endgroup\$