无法理解Python的代码行

时间:2020-09-08 16:58:38

标签: python python-3.x flask

我是初学者,正在学习烧瓶。做运动时,我看不懂一些代码。谁能解释一下for循环这一行?

@app.route("/details/<int:pet_id>")
def pet_details(pet_id):
    pet = next((pet for pet in pets if pet["id"] == pet_id), None) 
    if pet is None: 
        abort(404, description="No Pet was Found with the given ID")
    return render_template("details.html", pet = pet)

我无法从代码中理解这一行

    pet = next((pet for pet in pets if pet["id"] == pet_id), None)

1 个答案:

答案 0 :(得分:3)

next从生成器中获取下一项,在本例中为(pet for pet in pets if pet["id"] == pet_id)。该生成器会将您的pet对象的列表/集合减少为仅其ID与所请求的pet_id相同的对象。

这里的None是默认值:如果生成器没有下一个元素,则通常会抛出StopIteration异常,但是在这种情况下,next将处理该异常,而不会返回一个None对象,而不是抛出错误

相关问题