I have a function below that should be constantly running every second, making api calls and receiving data. Api_data is an instance of a class defined separately. I am building a list with 5 most recent data points. I want to be able to use my_DataPoints in other functions and modules, for example to build a json with the received recent data and I am not sure how to pass and access its value. I defined global variables but I am not sure if this is the correct way and how to import them. I would appreciate your help
def get_data(api_data):
interval= 5
global my_DataPoints
global myData
my_DataPoints= []
myData = {}
while True:
for x in range(interval):
start= time.time()
myData= api_data
print(myData.rTime)
my_DataPoints.append(myData)
if (len(my_DataPoints)-1) ==interval:
my_DataPoints.pop(0)
print(my_DataPoints)
end= time.time()
if (end -start) < 1:
time.sleep(1-(end-start))
>Solution :
Instead of using global variables, you can define your get_data function to return the my_DataPoints list after it’s done collecting the data. Then, you can assign the returned list to a variable in your main script, which you can then pass to other functions.
Here’s an example of how you can modify your get_data function to return the my_DataPoints list:
def get_data(api_data):
interval= 5
my_DataPoints= []
myData = {}
while True:
for x in range(interval):
start= time.time()
myData= api_data
print(myData.rTime)
my_DataPoints.append(myData)
if (len(my_DataPoints)-1) ==interval:
my_DataPoints.pop(0)
print(my_DataPoints)
end= time.time()
if (end -start) < 1:
time.sleep(1-(end-start))
yield my_DataPoints
In your main script, you can then call the function and assign the returned list to a variable like this:
api_data = ApiData() # assuming ApiData is the class for your API data
data_points = get_data(api_data) # get the generator object
while True:
my_DataPoints = next(data_points) # get the next set of data points
# do something with my_DataPoints, e.g. build a JSON object
time.sleep(1) # wait for 1 second before getting the next set of data points
Note that get_data now returns a generator object that yields the my_DataPoints list every interval seconds. The next function is used to retrieve the next set of data points. You can then use the my_DataPoints list as needed in your main script.