I am building a simple flask app and I was wondering if I could perform one action like we do in the finally
block after a try-except
block but ONLY if the try succeeded and AFTER a return
statement in the try block.
I tried else
but else
does not execute after return
.
This is short of what I would like to do:
def delete(self,pet_id):
if pet_id:
pet = None
try:
pet = [pet for pet in self.pets if pet.get("id")==pet_id][0]
return jsonify({"pet": pet}), HTTPStatus.OK
except Exception as exc:
return (
f"The pet id provided: {pet_id}, does not exist",
HTTPStatus.BAD_REQUEST,
)
else:
self.pets.remove(pet)
CodePudding user response:
You could short of check if the operation that you wanted to achieve is indeed completed and then remove the variable like so:
def delete(self,pet_id):
if pet_id:
pet = None
try:
pet = [pet for pet in self.pets if pet.get("id")==pet_id][0]
return jsonify({"pet": pet}), HTTPStatus.OK
except Exception as exc:
return (
f"The pet id provided: {pet_id}, does not exist",
HTTPStatus.BAD_REQUEST,
)
finally:
if pet:
self.pets.remove(pet)
CodePudding user response:
This is how you need to structure your code for it to work:
def delete(self,pet_id):
if pet_id:
try:
pet = [pet for pet in self.pets if pet.get("id")==pet_id][0]
self.pets.remove(pet)
return jsonify({"pet": pet}), HTTPStatus.OK
except Exception as exc:
return (
f"The pet id provided: {pet_id}, does not exist",
HTTPStatus.BAD_REQUEST,
)
There is no point in running the remove()
call if pet_id
is not found.