Python - 奇怪的UnboundLocalError

时间:2013-01-12 03:26:46

标签: python

当我运行以下功能时:

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

我得到了

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

这对我没有意义。我没有全局变量响应。我希望它通常如下工作。

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

任何人都知道我为什么会收到此错误?

2 个答案:

答案 0 :(得分:1)

您的代码没有正确缩进。将其更改为此并且它将起作用(可能不是预期的,但它会起作用):

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!')

发生错误的原因是您在response循环中定义for,但如果循环未运行(即userLinks == []),则永远不会设置该变量。

答案 1 :(得分:1)

你正在混合制表符和空格。查看您粘贴的原始代码:

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

您可以在最后一行看到开关。实际上,这意味着html = response.read()行没有按照您的想法缩进,这意味着如果userLinks为空,您将获得:

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

使用python -tt yourprogramname.py运行您的代码以确认此问题,并切换为始终使用四个空格标签。