UnboundLocalError: local variable 'url' referenced before assignment

Question:

I’m trying to get this code working, but it keeps coming up with the error in the title. I don’t get it. The function “url” is set before the “get_media” function, and the same function call thing works with other functions I’ve set, but it says otherwise. I’ve looked at similar question’s answers, but I cannot understand any of them, because the answers are designed around their complicated code, and they offer up no proper explanation as to how it works.

def url(path):
    if path.find("?") != -1:
        pre = "&"
    else:
        pre = "?"
    return protocol +"://" +host +base_path +path +pre +"access_token=" +access_token

def get_media(insta_id, max_id=None):
    insta_id = str(insta_id)
    path = url("/users/%s/media/recent/") # ERROR COMES UP HERE
    if max_id is not None:
        path = path +"&max_id=%s" % max_id
    url = urllib.request.urlopen(path)
    url = url.read().decode("utf-8")
    url = json.loads(url)
    return url

Any help appreciated. Tell me if you need more code to work with.

B

Asked By: Bob

||

Answers:

You assign to a local variable called “url” later in your function. Because of that, Python treats every reference to “url” within that function as local. But of course you haven’t defined that local variable yet, hence the error.

Use a different name for the local “url” variable. (It’s never a URL anyway, so you should definitely use a better name.)

Answered By: Daniel Roseman

Just need to tell python this is global variable inside function

url = "" # <------ 1. declare url outsite function/def
def get_media():
    global url  # <-------- 2. add here "global" tell the system this is global variable
    # .... 
    url = "my text"
    print(url) # will display "my text"
Answered By: Shawn Lee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.