-1

I have a question and code given below. This is the normal scenario where script2 calls script1 which returns a dataframe. lets say, I have script3,4,5 which needs dataframe1 from script1, everytime, I call script1 from other scripts, script1 will get executed every time it is called. so, instead is there a way script1 is called only once and other scripts pulls/takes dataframe1 from script1?

script1()
code...
return dataframe1

script2()
from script1 import *
dataframe = script1()
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • Does this answer your question? [Efficient way of having a function only execute once in a loop](https://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop) – quamrana Jun 25 '20 at 15:05

1 Answers1

0

Assuming by scriptN you mean different modules, you could just have the first module cache the result and return that on subsequent calls. Something like this:

# script1.py
_df = None

def get_dataframe()
    global _df
    if _df is None:
        _df = calculate_dataframe()
    return _df

def calculate_dataframe():
    # Generate dataframe here
    return the_dataframe

Now you can use it from other modules and it'll only get calculated the first time:

# script2..N.py
from script1 import get_dataframe
df = get_dataframe()
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • Actually, I am getting data from a website every 30secs. output of this website data is stored in dataframe which is script1. I have script 2 and 3 which requires the dataframe from script1. so if I invoke script1 sequentially from script 2 & 3, each time script1 is called and dataframe with new values are returned to script 2 and 3. – Dhayalamoorthi Mani Jun 25 '20 at 15:56
  • @DhayalamoorthiMani Your question makes even less sense then; do you want it to be called multiple times or not? Maybe if you explained more of your actual code it'd be understandable. – tzaman Jun 25 '20 at 21:02
  • Hi, let me briefly tell you: script1 keeps collecting data from website every 30secs. I want this script1 to run in an infinite loop so that every 30secs, any new data in website will be retrieved and stored in dataframe. I have script2 and script 3 which depends on script1 output. so, as in old days, I am returning the dataframe from script1 which stops the script1 and gives the output to script2 and 3.... so what I wanted is script1 should run in an infinite loop and scrip2&3 should come and take output of script1. so ideally script1 will not have any return statement.. pls explain thanks – Dhayalamoorthi Mani Jun 29 '20 at 11:02
  • @DhayalamoorthiMani You'll need to have `script1` running on a separate thread or process for that to work, and build some kind of message passing or producer/consumer mechanism. That's way beyond the scope of this question; I'd start by reading up on multithreading. – tzaman Jun 29 '20 at 11:25