Reputation: 1105
I want to write a function to exit a for loop. Typically, we can
for i in range(10):
if i==8:
break
I hope to write a function like,
def interrupt(i):
if i == val:
...
for i in range(10):
interrupt(i)
Edit
I understand the mechanism and why I can't do this now. Just out of curiosity, does python offer something like 'macro expansion', so that I don't actually create a function, but a name to repalce the code block?
Upvotes: 2
Views: 74
Reputation: 4487
The following code will solve your problem:
def interrupt(i, pred=lambda x:x==8):
if pred(i):
raise StopIteration(i)
try:
for i in range(10):
interrupt(i)
except StopIteration as e:
print('Exit for loop with i=%s' % e)
# output: Exit for loop with i=8
The scheme is simple, and works in general with any kind of exception:
foo()
that raises one or more exceptions when one or more events occurfoo()
in the try-except constructUpvotes: 2
Reputation: 7510
I don't think it is possible to throw a break, you can fake it a bit like this for example:
def interrupt(i):
if i > 2:
return True
return False
for i in range(10):
if interrupt(i):
break
#.. do loop stuff
Upvotes: 3
Reputation: 532238
You can't. The for
loop continues until an explicit break
statement is encountered directly in the loop, or until the iterator raises StopIteration
.
The best you can do is examine the return value of interrupt
or catch an exception raised by interrupt
, and use that information to use break
or not.
Upvotes: 3