From what I understand, a for x in a_generator: foo(x)
loop in Python is roughly equivalent to this:
try:
while True:
foo(next(a_generator))
except StopIteration:
pass
That suggests that something like this:
for outer_item in a_generator:
if should_inner_loop(outer_item):
for inner_item in a_generator:
foo(inner_item)
if stop_inner_loop(inner_item): break
else:
bar(outer_item)
would do two things:
- Not raise any exceptions, segfault, or anything like that
- Iterate over
y
until it reaches somex
whereshould_inner_loop(x)
returns truthy, then loop over it in the innerfor
untilstop_inner_loop(thing)
returns true. Then, the outer loop resumes where the inner one left off.
From my admittedly not very good tests, it seems to perform as above. However, I couldn't find anything in the spec guaranteeing that this behavior is constant across interpreters. Is there anywhere that says or implies that I can be sure it will always be like this? Can it cause errors, or perform in some other way? (i.e. do something other than what's described above
N.B. The code equivalent above is taken from my own experience; I don't know if it's actually accurate. That's why I'm asking.