1

This might not be possible but if it is, I want to know how can it be done?

Here is my code-structure

for item in somelist:
    # Calcuating some stuff

inside my for loop, I have some evaluation to do which might cause exception.
and even if I handle the exception, current iteration is passed as in complete
What I want to do is, if I get exception, I want to re-evaluate current iteration with some new information.
Is it possible?
Example

for item in somelist:
    try:
        # calculating item
    except Exception:
        # re-running current iteration (not from the beginning)
3
  • Might want to take care - if re-evaluation results in another exception ... and so on ... you could end up with an infinite loop. Commented Jun 6, 2022 at 15:45
  • Not possible. The for loop uses the iterator protocol, which means the only thing it can do (after using iter(somelist) to get the iterator in the first place) is call next on that iterator. Commented Jun 6, 2022 at 15:47
  • What you can do is put another loop in the body of the for loop which doesn't exit until you are finally done with item and ready to get the next value. Commented Jun 6, 2022 at 15:47

2 Answers 2

3

I'd suggest using an inner loop to handle the retry:

for item in somelist:
    while True:
        try:
            # calculating item
            break  # breaks inner loop, outer loop continues
        except Exception:
            # get new information, inner loop continues implicitly

If you want to retry a limited number of times to avoid the possibility of an infinite loop, that's easily accomplished by making the inner loop something like for _ in range(NUM_RETRIES).

Sign up to request clarification or add additional context in comments.

Comments

1

If you're using a list try using while instead of for loop

i = 0
while i < len(somelist):
  item = somelist[i]
  try:
        # calculating item
  except Exception:
    i -= 1
  i += 1

Comments

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.