0

This is difficult even to explain; I apologise in advance if it sounds confusing.

In Python 3 I have a function: foo().

The first time I call this function it needs to make some complicated calculations that only needs to be done once every time I run the program. Then the result of those calculations needs to be used. I would like the person calling foo not to have to bother with all this. So they just can call foo() multiple times when they need it. Without having to know that the first time there are some extra work being done.

In a sense I need foo to set up some persistent variables. Where persistence does not mean from one instance of the program to the other but from one instance of the function to the other.

Maybe I could set up a global variable defined inside the function but this is not really good style. Also the program needs to be really fast, so I don't want to store it on disk. What alternatives do I have?

foo_variable=""

def foo():
     global foo_variable
     if foo_variable=="":
         foo_variable=slow_calculations_only_to_be_done_once()
     return fast_calculations_using_foo(foo_variable)

print (foo())
print (foo())

Eventually I would like foo to be in a library that get's imported and called in the most simple way. Thanks.

Pietro Speroni
  • 3,131
  • 11
  • 44
  • 55
  • See also [Is there a decorator to simply cache function return values?](https://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values) – raul.vila Apr 20 '18 at 11:05
  • If your function accepts argument and `foo_variable` depends on it you can simply use a `lru_cache`. – Mazdak Apr 20 '18 at 11:06

0 Answers0