There is a way to put some condition in the For syntax?

i want to have the posibility of abort a For, but is a for that runs over a method (i think that would be the word). I dont have control over this method.

the code is more or less like this:

if started:
        print("Inside started")
        for event in board.stream_incoming_events():
            print("IM not here!!!!")

This is stream_incoming_events:

If nothing arrive this just keep waiting…

I suppose i could put this for event inside another thread and kill him, but… it will be nice if i dont have to do that. So, maybe “for” have a way to abort the for in the initial line? because i never go to the print(im not here!!!)

maybe some:

for event in (board.stream_incoming_events(), except ThisVariable is True):

or maybe there is something similar to “for” but with this “option”?

That function is called a generator (the use of yield is often a clue about that).

If you want the generator to return after some sort of timeout, that will have to be in the generator’s code, there are no straightforward ways to do it from outside as far as I know. In your example of breaking out of the loop if ThisVariable is True, you could just do that in the loop body by using break.

In the generator, if you want it to stop returning results, it either needs to return (and not yield), or raise an exception that you can catch.

1 Like