Issue
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)
Solution
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)
Answered By - DataCoder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.