0

I found this in the Python docs:

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally clause within that loop. It continues with the next cycle of the nearest enclosing loop.

As the continue-instruction is not made for the with-statement: Is there any alternative other than restructuring the code appropriately?

Example code (the way I want it to be working):

with open("test.txt", "r") as f:
    if someConditionNotMet(f):
        continue  # "exit" with-statement
    # do lots of stuff

Of course I could write the # do lots of stuff-code inside an else-branch, however, this would only make the code less readable, if there are already two or three nested if-else-branches. In a function I could simply use return and in a while- or for-loop the beforementioned continue. Is there an equivalent to continue in a Python's with-statement?

Well, you could also replace the continue by a break in the text above, logically it would be the same in a with-statement as the code inside it is only executed once, anyway... (but the break only works for for- and while-loops, either).

mozzbozz
  • 3,052
  • 5
  • 31
  • 44
  • 1
    A `with` statement isn't a looping construct, so `continue` doesn't really make sense in that context. You can't use `continue` in an `if` either. – Charles Duffy Nov 27 '14 at 13:35
  • @CharlesDuffy: Yeah, I noticed this just after posting my question. See the last paragraph which I've added about it. – mozzbozz Nov 27 '14 at 13:37
  • 1
    Incidentally, there's a too-clever-by-half use of a context manager to add exception management support to `with` blocks provided as an answer in the question this is a duplicate of; it certainly does what you want. That said, I'd say that the _best_ approach is to structure your code to have a separate function in use and `return`. – Charles Duffy Nov 27 '14 at 13:41
  • @fredtantini: You are right. Voted for close. **Thanks** for the link! I did not find this, no matter which search keys I tried :/ So basically there's no such equivalent... Only way is to restructure the code in an appropriate way :/ Well, not the answer I hoped to find, but the one I feared to get :D – mozzbozz Nov 27 '14 at 13:41

0 Answers0