关于python:在赋值json之前引用的局部变量

local variable referenced before assignment json

每样东西都能完美地工作几个小时,然后我会得到这个错误,它会停止运行。

1
2
todolist_items = len(todoalso)
UnboundLocalError: local variable 'todoalso' referenced before assignment

我想这是我遇到麻烦的部分,但我不明白为什么。

1
2
3
4
5
    response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
    todoalso = response.json()
global todolist_items
todolist_items = len(todoalso)


您需要捕获响应失败的案例,并将其记录以了解原因。

1
2
3
4
5
if response.status_code == 200:
    todoalso = response.json()
else:
    todoalso = None
    print response.status_code,response


我会比其他人更进一步,并提出以下建议:

1
2
3
4
5
6
7
8
9
10
response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
global todolist_items

if response.status_code == 200:
    todoalso = response.json()
    # Let's assign this variable here, where we know that the status code is 200
    todolist_items = len(todoalso)
else:
    # instead of simply assigning the value"None" to todoalso, let's return the response code if it's not 200, because an error probably occurred
    print response.status_code


在这种情况下,我认为响应代码不是200,因此它直接转到

1
todolist_items = len(todoalso)

没有在if分支中分配。也许把它修改为

1
2
3
4
5
    response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
    todoalso = response.json()
    global todolist_items
    todolist_items = len(todoalso)

正如@resetack建议的那样,我添加了一些更改

1
2
3
4
5
6
7
    response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
if response.status_code == 200:
    todoalso = response.json()
    global todolist_items
    todolist_items = len(todoalso)
else:
    requests.raise_for_status()