vendredi 23 janvier 2015

An if statement to check within try statement in Python, need the code to execute in case an exception is raised as well.

I'm a bit stumped here. Here's a piece of Python code:



try:
if parse[index+1][0] != "5":
individual_services+=[individual_services_cur]
individual_services_cur=[]
except IndexError:
warning("Reached end of file. No next element")
individual_services+=[individual_services_cur]
individual_services_cur=[]


Basically I want these two actions (addition of individual_services_cur list to individual_services list and clearing of individual_services_cur list) to take place either if the next element in parse is not "5" or if it doesn't exist (basically it is the end of file).


I am wondering if there is a more elegant way to write this code, for example, without the need to write these two actions twice. I couldn't think of any good solution with finally or else statements, and it seems that I cannot get rid of try statement because once the end of file is reached, the IndexError exception is inevitably raised.


Aucun commentaire:

Enregistrer un commentaire