I found this in the Python docs:
continue
may only occur syntactically nested in afor
orwhile
loop, but not nested in a function or class definition orfinally
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).