UnboundError: local variable ‘item_url’ referenced before assignment

huangapple go评论112阅读模式
英文:

UnboundError: local variable 'item_url' referenced before assignment

问题

在另一个函数中,URL 是一个单独的变量,一切正常运行。

  1. def afd(url):
  2. url = '...'
  3. ...
  4. links = [...]
  5. async def ...(...):
  6. items = [...]
  7. result_id = ...
  8. for i in range(5):
  9. if result_id == items[i].id:
  10. item_url = links[i]
  11. break
  12. afd(item_url)

我尝试了什么都没有,因为我在这里没有看到任何问题,也不知道如何修复它。一些互联网上的解决方案没有起作用。

英文:

In another function where URL is a separate variable everything works fine

  1. def afd(url):
  2. url = '...'
  3. ...
  4. links = [...]
  5. async def ...(...):
  6. items = [...]
  7. result_id = ...
  8. for i in range(5):
  9. if result_id = items[i].id:
  10. item_url = links[i]
  11. break
  12. afd(item_url)

I tried nothing because I don't see any problems here and have no idea how to fix it. Some solutions from the internet didn't work

答案1

得分: 0

根据错误信息显示,您正在引用一个未分配的变量。
在这种情况下,只有在满足条件result_id = items[id].id时,才会分配item_url,但这是不可能的,因为您只是在评估一个赋值语句(例如 x = 10)而不是一个语句(例如 x == 10)。

即使在修复语句后,变量item_url也只会在item.id有效的情况下分配,您应该在item.id无效的情况下定义一个默认值(例如item_url = [],假设每个项目都有一个不同的URL),或者在if体内使用该变量。

选项1

  1. def afd(url):
  2. url = '...'
  3. ...
  4. links = [...]
  5. async def ...(...):
  6. items = [...]
  7. result_id = ...
  8. items_url = [] // 默认值
  9. for i in range(5):
  10. if result_id == items[i].id: // 正确的比较语句
  11. items_url[i] = links[i] // 添加有效的item_url
  12. break
  13. for item_url in items_url:
  14. afd(item_url) // 对每个有效的item_url调用afd

这绝不是最佳实现,而只是基于您提供的代码片段的教育性尝试。

英文:

As the error says, you are referencing a variable that is not assigned.
In this case item_url only get assigned if the condition result_id = items[id].id is met, which it's impossible as you are just evaluating an assignment (e.g x = 10) and not a statement (eg x == 10).

And even after fixing the statement, the variable item_url only is assigned for cases in which the item.id is valid, you should define a default value (e.g item_url = [] assuming there is a different url for each item) in case the item.id is invalid or use the variable inside your if body.

Option 1

  1. def afd(url):
  2. url = '...'
  3. ...
  4. links = [...]
  5. async def ...(...):
  6. items = [...]
  7. result_id = ...
  8. items_url = [] // default value
  9. for i in range(5):
  10. if result_id == items[i].id: // Correct comparison statement
  11. items_url[i] = links[i] // Add valid item_url
  12. break
  13. for item_url in items_url:
  14. afd(item_url) // Invoke afd over every valid item_url

This is by no means the best implementation but more an educational attempt based on your snippet of code.

huangapple
  • 本文由 发表于 2023年5月7日 23:33:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定