TheoretiCAL
TheoretiCAL

Reputation: 20571

Python - Weird UnboundLocalError

When I run the following function:

def checkChange():
    for user in userLinks:
        url = userLinks[user]
        response = urllib2.urlopen(url)  
        html = response.read()

I get

Traceback (most recent call last):
  File "InStockBot.py", line 34, in <module>
    checkChange()
  File "InStockBot.py", line 24, in checkChange
    html = response.read()
UnboundLocalError: local variable 'response' referenced before assignment

Which makes no sense to me. I have no global var response. I expect it to work as below, normally.

>>> url="http://google.com"
>>> response = urllib2.urlopen(url)  
>>> html = response.read()
>>> html
'<!doctype html>

Anyone know why I get this error?

Upvotes: 1

Views: 214

Answers (2)

DSM
DSM

Reputation: 353449

You're mixing tabs and spaces. Looking at the raw code you pasted:

'    def checkChange():'
'    \tfor user in userLinks:'
'    \t\turl = userLinks[user]'
'    \t\tresponse = urllib2.urlopen(url)  '
'            html = response.read()'

You can see the switch in the last line. Effectively, this means that the html = response.read() line isn't indented as far as you think it is, meaning that if userLinks is empty, you'll get:

Traceback (most recent call last):
  File "inde.py", line 10, in <module>
    checkChange()
  File "inde.py", line 5, in checkChange
    html = response.read()
UnboundLocalError: local variable 'response' referenced before assignment

Run your code using python -tt yourprogramname.py to confirm this, and switch to always using four-space tabs.

Upvotes: 1

Blender
Blender

Reputation: 298472

Your code isn't indented properly. Change it to this and it'll work (probably not as intended, but it will work):

for user in userLinks:
    url = userLinks[user]
    response = urllib2.urlopen(url)  
    html = response.read()

    if userSources[user] != html:
        del userSources[user]
        del userLinks[user]
        api.PostDirectMessage(user,'It appears the page has updated! Your item may be back in stock!')

The error occurs because you define response in the for loop, but if the loop doesn't run (i.e. userLinks == []), that variable is never set.

Upvotes: 1

Related Questions