0

Somethimes i got a error that the function call dont return graph_data["value"], so i tried put it inside a try except block and made a recursive call to the function. But I am receiving

UnboundLocalError: local variable 'obj' referenced before assignment

I am using flask.

def get_chart_images(dam, chart_name, chart_path):
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    url = "https://graph.microsoft.com/v1.0/" + chart_path + "/Image(width=800,height=600,fittingMode='fit')"
    try:
        graph_data = requests.get(  # Use token to call downstream service
            url,
            headers={'Authorization': 'Bearer ' + token['access_token']},
            ).json()
        
        obj = {
            "dam": dam,
            "chart_name": chart_name,
            "chart_image": graph_data["value"]
        }  
    except:
        #trying call again the function
        get_chart_images(dam, chart_name, chart_path)

  
    return obj

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • The recursive call is utterly pointless, because you throw away its return value. You'd need to assign it to `obj`, so that *this* call of the function has a value to return. – jasonharper Oct 20 '22 at 01:25
  • Welcome to Stack Overflow. The problem is that simply calling `get_chart_images(dam, chart_name, chart_path)` recursively **does not cause** `obj` to change in the **current** call, because `obj` is a **local** variable. It is the same problem as in the linked duplicate, although the effect is different (because your code has a different surrounding logical structure). That said, **please do not use recursion** for a simple "try until it works" loop. Just use a `while` loop. It's easier to understand and does not risk stack overflow. (Python **does not** do tail-call optimization.) – Karl Knechtel Oct 20 '22 at 05:16

0 Answers0