Let's say we have a generator that is indefinite, where new elements can arrive at any moment with significant (up to indefinite) delay.An example of such generator is tail -F command. In python (omitting various edge cases) it could be implemented as the following:def tail_follow(file):    while True:        line = file.readline()        if line:            yield line        else:            sleep(1.0)Obvious problem with this generator is that it may cause caller's thread to sleep forever. Therefore it should provide caller's side a way to break iteration.The solution I came up is the following:def tail_follow(file, on_delay_callback):    while True:        line = file.readline()        if line:            yield line        else:            if on_delay_callback():                break            else:                sleep(1.0)Is this the only way to get this behavior with Python? I know that there is a send function that allows 2-way data transfer, can it be used to make solution more pythonic?
How to properly handle indefinite generators in Python
python;python 3.x;iterator
I don't see the problem with your approach. I think you are almost there. If you change your generator to yield None when there is nothing to return, then you can simply test for that.See the following example:#!/usr/bin/pythonimport sysimport timetailpath = ./tailfilefd = open(tailpath)def tail_follow(file):    while True:        line = file.readline()        if line:            yield line        else:            yield Noneif __name__ == __main__:    for line in tail_follow(fd):        if line:            print (found: %s % (line))        else:            # do something useful            time.sleep(1.0)Or alternatively:if __name__ == __main__:    mytail = tail_follow(fd)    while True:        # do something useful        time.sleep(1.0)        # anything to tail ?        line = next(mytail)        if line:            print (found: %s % (line))Jeff Knupp has a nice post about infinite generators.