1

I've got some Python code as follows:

for emailCredentials in emailCredentialsList:
   try:
       if not emailCredentials.valid:
           emailCredentials.refresh()
   except EmailCredentialRefreshError as e:
       emailCredentials.active = False
       emailCredentials.save()
       # HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP 
       # SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW?

   # a lot more code here that scrapes the email box for interesting information

And as I already commented in the code, if the EmailCredentialRefreshError is thrown I want this iteration of the for loop to stop and move to the next item in the emailCredentialsList. I can't use a break because that would stop the whole loop and it wouldn't cover the other items in the loop. I can of course wrap all the code in the try/except, but I would like to keep them close together so that the code remains readable.

What is the most Pythonic way of solving this?

0

1 Answer 1

5

Try using the continue statement. This continues to the next iteration of the loop.

for emailCredentials in emailCredentialsList:
   try:
       if not emailCredentials.valid:
           emailCredentials.refresh()
   except EmailCredentialRefreshError as e:
       emailCredentials.active = False
       emailCredentials.save()
       continue
   <more code>
Sign up to request clarification or add additional context in comments.

4 Comments

this will work, of course; but do you have a citation (e.g., PEP) that this is the Pythonic way to do it?
@mfrankli well the only other way would be to move the whole rest of the loop body into the try's else block, and "flat is better than nested", not to mention that (as the OP points out) this makes it harder to understand the control flow as the continue is a long way from the for.
break and continue are valid statements and it would be pythonic. But as @jonrsharpe mentioned, you can call raise in exception and handle the unexceptional part in the else block too. It is all about flavour and taste
@jonrsharpe, "Flat is better than nested" is exactly the sort of thing I was looking for; since the question explicitly asks for "most Pythonic", it seemed important to cite something like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.