1

I am a beginner and learning flask. While doing an exercise, I can't understand some code. Can anyone explain me the line with for loop?

@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)

I can't understand this line from code

    pet = next((pet for pet in pets if pet["id"] == pet_id), None)
jarmod
  • 71,565
  • 16
  • 115
  • 122

1 Answers1

3

next gets the next item from a generator, which in this case is (pet for pet in pets if pet["id"] == pet_id). This generator will reduce your list/collection of pet objects to only those whose id is the same as the requested pet_id.

The None here is defaulting: if the generator has no next element, it'll typically throw a StopIteration exception, but in this case, next will handle the exception and instead return a None object instead of throwing an error

M Z
  • 4,571
  • 2
  • 13
  • 27