I need a watchdog mecanism to prevent infinite loops. This would look like this:
def stop(n):
""" Returns False after n calls """
for _ in range(n):
yield True
yield False
and I would use it this way:
def foo():
# this is the function I have to watch
return True # not good!
while foo() and stop(1000):
# do some stuff
Of course the above code does not work because stop(1000) is an iterator. I could write a function that mimics stop(), by using a global variable, but it would not be very pythonic. I can also write like this:
for _ in range(n):
if not foo():
break
# do_some_stuff()
It works, but not very elegant, because range(n) is of secondary importance. Is there any Python magic that would make this code elegant?