You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UnboundLocalError报错求助:变量'todoalso'未赋值即引用

解决UnboundLocalError: local variable 'todoalso' referenced before assignment

Hey, let's break down exactly what's causing this crash. That UnboundLocalError pops up because your todoalso variable only gets defined inside the if response.status_code == 200: block.

Think about it: your program ran fine for hours because the Todoist API was returning 200 OK responses. But eventually, something went wrong—maybe a network glitch, an expired token, or a server error—and the request returned a non-200 status code. When that happened, the code inside the if block never ran, so todoalso was never created. But your code still tries to calculate len(todoalso) anyway, which throws the error.

Looking at your original code snippet:

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)

There's another small issue too: declaring global todolist_items inside the if block works, but it's messy—anyone reading your code might miss that you're modifying a global variable unless it's at the top of the function.

Here's how to fix this properly:

  • Initialize todoalso with a default value before the if statement, so it exists no matter what request outcome you get. An empty list is perfect here since you're checking its length.
  • Move the global declaration to the top of your function (assuming this code is inside a function, which it must be to use global).
  • Add handling for non-200 status codes so you can log the issue and set a safe default for todolist_items instead of crashing.

Fixed code example:

def update_todo_list():
    global todolist_items  # Declare global at the start of the function
    todoalso = []  # Default empty list to avoid undefined variable errors
    
    response = requests.get("https://beta.todoist.com/API/v8/tasks", params={"token":todoist_TOKEN})
    
    if response.status_code == 200:
        todoalso = response.json()
        todolist_items = len(todoalso)
    else:
        # Log the failure so you can debug later
        print(f"Failed to fetch Todoist tasks: Status code {response.status_code}")
        # Set a safe default value
        todolist_items = 0

A quick best practice note:

If you can avoid using global variables, do it. They make code harder to debug and maintain. Consider returning todolist_items from the function instead, and passing it where you need it in your program.

内容的提问来源于stack exchange,提问作者john smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:15:31