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?