0

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

Bob
  • 15
  • 1
  • 4
  • looks like you're using 'url' as both a function and a local variable, change the name of one of them. – bj0 Apr 07 '15 at 17:35
  • Try renaming your function `url`. I don't know for certain, but my guess is that if `get_media` is called once, the function will be removed. On the second call, `path = url(...)` can't find the reference. – Spice Apr 07 '15 at 17:35

2 Answers2

1

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.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

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"
Shawn Lee
  • 41
  • 4