1

I have a python program that gets data from an API. This data changes every few minutes. The program currently runs without any issue other than my refresh function that is called in multiple places.

Sample code:

import requests
import json
import time

url = 'https://api.url.com/...'

resp = requests.get(url)
data = resp.json()

def refresh_data():
     resp = requests.get(url)
     data = resp.json()

while True:
     print(data)

     #This will not refresh the response
     refresh_data()

     #This will refresh (But I need it in function)
     #resp = requests.get(url)
     #data = resp.json()

     sleep(60)

I would like any suggestions on how to make my refresh function work. I will be calling it from other functions as well as other python files.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Stivan
  • 1,128
  • 1
  • 15
  • 24

2 Answers2

2

The data variable that you are using in the refresh() function, is not the global variable that you've created, but, a local variable which is not accessible outside the function.

To use that variable outside the function, you can do 2 things here:

  1. Change the refresh() function to return the new data:

    def refresh_data():
        resp = requests.get(url)
        data = resp.json()
        return data
    
    while True:
        print(data)
        data = refresh_data()
    
  2. Make the variable data global:

    def refresh_data():
        global data
        resp = requests.get(url)
        data = resp.json()
    
    while True:
        print(data)
        refresh_data()
    

I recommend you to use the first solution, as using global variables is not at all a good practice.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
1

Your data object is defined in the global scope, but when you assign to it from within a function, that creates a new local variable that overshadows the global scope one. You need to specify the fact that you mean to assign to the global variable as such:

def refresh_data():
     global data
     resp = requests.get(url)
     data = resp.json()